Search code examples
htmliosswiftpdfwkwebview

Since iOS 14 creating a PDF from a Webview not working correctly


Before iOS 14 I had a function createPDF_Specs that created a DIN A4 PDF for me from a web view. Since iOS14 however it moves the background picture of the webview (which is created from a htmlString) to a second site in the PDF. The strange thing is, that the webview is shown correctly.

The first picture shows how the web view is seen and the second one how the PDF ends up.Webview FinalPDF

func createPDF_Specs(formatter: UIViewPrintFormatter, filename: String) -> String {
        // From: https://gist.github.com/nyg/b8cd742250826cb1471f
        
        // 2. Assign print formatter to UIPrintPageRenderer
        let render = UIPrintPageRenderer()
        
        
        render.addPrintFormatter(formatter, startingAtPageAt: 0)
        
    
        // 3. Assign paperRect and printableRect
        let page = CGRect(x: 0, y: 0, width: 841.8, height: 595.2) // A4, 72 dpi
        let printable = page.insetBy(dx: -3, dy: -3)
    
        render.setValue(NSValue(cgRect: page), forKey: "paperRect")
        render.setValue(NSValue(cgRect: printable), forKey: "printableRect")
        
        // 4. Create PDF context and draw
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, page, nil)
    
    print(render.numberOfPages, "Number of pages")
        for i in 1...render.numberOfPages {
            
            UIGraphicsBeginPDFPage();
            let bounds = UIGraphicsGetPDFContextBounds()
            print(bounds)
         //   render.drawPage(at: i - 1, in: bounds)
            render.drawPage(at: i - 1, in: page)
        }
        
        UIGraphicsEndPDFContext()
        
        // 5. Save PDF file
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = "\(documentsPath)/\(filename).pdf"
        pdfPath = URL(string: filePath)
        pdfData.write(toFile: filePath, atomically: true)
        print("open \(filePath)")
        
        return filePath
}

Solution

  • Answer: This was an apple bug. I reported it to Apple and they fixed it with iOS 14.1