Generate a PDF from HTML template using WKWebview

Hello, We have functionality in an existing app, have to generate a pdf and it should be printable in the A4. The PDF is almost 8 to 10 pages

I have applied below solution:

Loading the HTML template on the WKwebview and doing a few operations on the content and converting it into a pdf.

  1. Converting the HTML into a string
  2. Replacing a few data with dynamic content

Issue:

The solutions worked fine in the previous OS(14.5,15.5,16.1), it is not working on the latest os 16.6

The Table background CSS is not Rendering. I have tried both Inline and external CSS loading but still facing the same issue.

Approch1:

func createPDF(formmatter: UIViewPrintFormatter, filename: String) -> String { let attributedString = NSAttributedString(string: "This is a test", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

    let printFormatter = UISimpleTextPrintFormatter(attributedText: attributedString)

    let render = UIPrintPageRenderer()

    render.addPrintFormatter(printFormatter, startingAtPageAt: 0)





    // 2. Assign print formatter to UIPrintPageRenderer

    //let render = UIPrintPageRenderer()

    render.addPrintFormatter(formmatter, startingAtPageAt: 0)



    // 3. Assign paperRect and printableRect

    let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi

    let printable = page.insetBy(dx: 20, dy: 20)

    //let printable = page.inset(by: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10));



    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, CGRect.zero, nil)



    for i in 1...render.numberOfPages {



        UIGraphicsBeginPDFPage();

        let bounds = UIGraphicsGetPDFContextBounds()

        render.drawPage(at: i - 1, in: bounds)

    }



    UIGraphicsEndPDFContext();



    // 5. Save PDF file

    var dst = self.getDestinationPath(1)

    if dst.contains("file://") {

        dst = dst.replacingOccurrences(of: "file://", with: "")

    }



    //let path = "\(NSTemporaryDirectory())\(filename).pdf"

    pdfData.write(toFile: dst, atomically: true)

    print("open \(dst)")



    return dst

}

}

Approach2:

But the pdf is Generating in a single page not multiple and it's not printable using the below solution.

func createPDFMethod(webView: WKWebView, title:String="samplepdf"){

let pdfConfiguration = WKPDFConfiguration()

/// Using `webView.scrollView.frame` allows us to capture the
// entire page, not just the visible portion
pdfConfiguration.rect = CGRect(x: 0, y: 0, width: webView.scrollView.contentSize.width, height: webView.scrollView.contentSize.height)

webView.createPDF(configuration: pdfConfiguration) { result in
    switch result {
    case .success(let data):
        // Creates a path to the downloads directory
        
        DispatchQueue.main.async {
            let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
            let pdfNameFromUrl = "\(title).pdf"
            let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrl)
            do {
                try data.write(to: actualPath, options: .atomic)
                print("pdf successfully saved!")
            } catch {
                print("Pdf could not be saved")
            }
        }

    case .failure(let failure):
        print(failure.localizedDescription)
    }
}

}

It seems the issue is with UIGraphics or WKwebview formaters.

could you please help me to resolve this issue?

l have the same issue - HTML background colours are not rendering on iOS 17 simulator and iOS 16.7 physical device. iOS 14 simulator device the colours render just fine. My coding follows a similar path going from HTML to PDF for printing.

Will continue digging for a solution.

If your issue is with HTML colours not rendering, be it the general background, table row or table cell backgrounds - I have just found a solution.

https://stackoverflow.com/questions/72507453/printing-from-wkwebview-in-swift-ignores-background/75882507#75882507

Have a look at the answer by ov1d1u

Adding this CSS directive to the HTML code fixed it for me:

@media print {
* {
    -webkit-print-color-adjust: exact !important;
  }
}

Phew, now I can continue.....

Generate a PDF from HTML template using WKWebview
 
 
Q