Search code examples
iosswiftpdfcore-graphicsios-pdfkit

Images are overwritten when modifying a PDF iOS


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:

enter image description here

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!


Solution

  • After reaching out to Apple's technical support. They concluded it was an issue with iOS 15.

    Here is a sample project that replicates the issue exactly: https://github.com/Manguelo/test-pdf-issue

    Note the application should be run on iOS 15.0

    According to the PDFKit team this bug should be addressed in iOS 15.2 beta 3.