SwiftUI - How to print HTML String to PDF?

How do I print a programmatically created HTML string to a PDF document?

SwiftUI doesn't have any special API for this. You'd likely need to look at the UIKit printing APIs: https://developer.apple.com/documentation/uikit/printing


Those APIs are geared towards sending data to a printer, but the UIPrintFormatter ultimately draws to a graphics context. You might be able to use a UIMarkupPrintFormatter to write to a CGPDFContextRef created using UIGraphicsBeginPDFContextToFile() or UIGraphicsBeginContextToData(). This would then call UIGraphicsBeginPDFPage() before calling UIPrintFormatter.draw(in:forPageAt:) to render each page.


Here's a rough skeleton, completely untested:


let html: String = ...
let outputURL: URL = ...
let formatter = UIMarkupTextPrintFormatter(markupText: html)

UIGraphicsBeginPDFContextToFile(outputURL.path, .zero, nil)
for pageIndex in 0..    UIGraphicsBeginPDFPage()
    formatter.draw(in: UIGraphicsGetPDFContextBounds(), forPageAt: pageIndex)
}
UIGraphicsEndPDFContext()
SwiftUI - How to print HTML String to PDF?
 
 
Q