Search code examples
iosswiftpdfnsdata

Generate multi-page PDF in Swift


I have an array of UIImage's i'd like to make into a long, multi-page PDF with one image per page. I have gotten as far as to make every image in to a PDF represented by NSData, but I'm struggling to find any information on how to combine them into one long document.

My current code looks like this:

 //Convert images to pdf
    var pdfDatas = [NSData]()
    for image in images {
        let pdfData = NSData.convertImageToPDF(image)

        pdfDatas.append(pdfData!)


    }
    //Combine PDF's to one long document here. 

Does anyone know how to achieve this?


Solution

  • are you using the CoreGraphics PDF functions? If so, I think you can use CGPDFContextBeginPage()/CGPDFContextEndPage() pairs before and after drawing each page's content.

    Something like

    CGPDFContextCreateWithURL(...)
    CGPDFContextBeginPage(...)
    
    // draw image using CGContextDraw functions
    
    CGPDFContextEndPage(...)
    

    There's more info in Apple's documentation here.