I have an application that allows a user to draw on a PDF. The user's drawing is saved as an image which is then added to an existing PDF. The issue I encounter is when a user has already drawn 2 images. For some reason, saving the 3rd image cause the 2nd image to be overwritten by the first. Below is an example.
PDF example:
The PDF above should read First, Second, Third; however, the 2nd image was overwritten by the first.
Below is my code for embedding an image into the PDF. Note I also tried this with PDFKit and have experienced the same result:
func saveImageToPDF(path: String , drawnImage: UIImage, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, pageIndex: Int) {
if let pdf = CGPDFDocument(NSURL(fileURLWithPath: path)) {
let pageCount = pdf.numberOfPages
// Write to file
UIGraphicsBeginPDFContextToFile(path, CGRect.zero, nil)
for index in 1...pageCount {
let page = pdf.page(at: index)
let pageFrame = page?.getBoxRect(.mediaBox)
if (pageFrame != nil) {
UIGraphicsBeginPDFPageWithInfo(pageFrame!, nil)
let pdfContext = UIGraphicsGetCurrentContext()
// Draw existing page
pdfContext?.saveGState()
pdfContext?.scaleBy(x: 1, y: -1)
pdfContext?.translateBy(x: 0, y: -pageFrame!.size.height)
pdfContext?.drawPDFPage(page!)
pdfContext?.restoreGState()
// Draw image on top of page
if (index == (pageIndex + 1)) {
drawnImage.draw(in: CGRect(x: x, y: y, width: width, height: height))
}
}
}
UIGraphicsEndPDFContext()
}
}
Note: I only seem to encounter this issue on iOS 15. Running the same code on iOS 14 works like a charm.
Should I consider this a bug on iOS 15, or is there something I'm missing?
Thanks in advance!