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
}