2
votes

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?

2

2 Answers

6
votes

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.

0
votes

Swift 5.5.2, Xcode Version 13.2.1.

Potential solution for an images placed on A4 format (one image per page), centred and keeping their aspect ratios.

Partly got inspired here on Ray Wenderlich tutorial on working with PDF

Take note of custom code I used in my solution:

PDFConstants.A4FormatRectangle is equal to CGRect(x: 0, y: 0, width: 595, height: 842)

Code you are looking for:

func getPDFDataFromImages(_ images: [UIImage], page rect: CGRect = PDFConstants.A4FormatRectangle) -> Data {
    
    let maxWidth        = rect.width
    let maxHeight       = rect.height
    
    var pdfData = Data()
    
    for image in images {
        let aspectWidth     = maxWidth / image.size.width
        let aspectHeight    = maxHeight / image.size.height
        let aspectRatio     = min(aspectWidth, aspectHeight)
        
        let scaledWidth     = image.size.width * aspectRatio
        let scaledHeight    = image.size.height * aspectRatio
        
        let imageYPosition  = (maxHeight - scaledHeight) / 2.0 // So it's centred on Y axis
        let imageXPosition  = (maxWidth - scaledWidth) / 2.0 // So it's centred on X axis
        let imageRect       = CGRect(x: imageXPosition, y: imageYPosition, width: scaledWidth, height: scaledHeight)
        
        let renderer = UIGraphicsPDFRenderer(bounds: rect)
        pdfData = renderer.pdfData { context in
            for image in images {
                context.beginPage()
                image.draw(in: imageRect)
            }
        }
    }
    
    return pdfData
}