I want to convert a UIImage array to a pdf file. PDF file page size should be A4. I tried with PDFKIT but the result is not appropriate.
What I want:
- A4 page size
- Image should be centered and scaled on the page(Array Images dimension is not identical)
What I tried:
func makePDF(images: [UIImage])-> PDFDocument? {
let pdfDoc = PDFDocument()
for (index,image) in images.enumerated() {
let resizedImage = resizeImage(image: image, targetSize: PDFPageSize.A4)
guard let cgImage = resizedImage?.cgImage else { return pdfDoc }
let uiimage = UIImage(cgImage: cgImage, scale: image.scale, orientation: .up)
if let pdfPage = PDFPage(image: uiimage) {
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
pdfPage.setBounds(page, for: PDFDisplayBox.mediaBox)
pdfDoc.insert(pdfPage, at: index)
}
}
return pdfDoc
}
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage? {
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
My Output is:
- Image missing
- Image Cropped
- Not in Center position
My Desire Output is:
How Can I do this?