Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing from WKWebView in Swift ignores background

I try to print html code to a pdf with the following code:

class PDFPrinter: NSObject, WKNavigationDelegate {
    
    static var shared = PDFPrinter()
    let webView = WKWebView()
    private var saveURL: URL!
    private var completion: () -> () = {}
    
    override init() {
        super.init()
        self.webView.navigationDelegate = self
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        let printInfo = NSPrintInfo(dictionary: [
            .paperSize: CGSize(width: 595.28, height: 841.89),
            .jobDisposition: NSPrintInfo.JobDisposition.save,
            .jobSavingURL: self.saveURL!,
        ])
        printInfo.horizontalPagination = .automatic
        printInfo.verticalPagination = .automatic
        let margin = 20.0
        printInfo.leftMargin = margin
        printInfo.topMargin = margin
        printInfo.rightMargin = margin
        printInfo.bottomMargin = margin
        let pro = self.webView.printOperation(with: printInfo)
        pro.showsPrintPanel = false
        pro.showsProgressPanel = false
        let selector = #selector(self.printOperationDidRun(printOperation: success: contextInfo:))
        pro.runModal(for: NSWindow(), delegate: self, didRun: selector, contextInfo: nil)
    }
    
    func printHTML(htmlString: String, saveURL: URL, completion: @escaping () -> ()) {
        self.saveURL = saveURL
        self.completion = completion
        webView.loadHTMLString(htmlString, baseURL: nil)
    }
    
    @objc func printOperationDidRun( printOperation: NSPrintOperation,
                                     success: Bool,
                                     contextInfo: UnsafeMutableRawPointer?){
        self.completion()
    }
    
}

This works except of one thing: The background of the html is completely ignored, my pdf is always completely white. I could not find any setting in WKWebView, NSPrintInfo or NSPrintOperation how to change that. Any ideas?

like image 363
Lupurus Avatar asked Oct 18 '25 12:10

Lupurus


2 Answers

I was having the same issue (seems that iOS 16.4 comes with a similar issue) and after hours of trying to solve that, it seems that this CSS directive fixes it for me:

@media print {
* {
    -webkit-print-color-adjust: exact !important;
  }
}
like image 142
ov1d1u Avatar answered Oct 21 '25 18:10

ov1d1u


in iOS 16 or above version compiler skips CSS part you have to tell them it is a IMPORTANT

Put this code in Style tag in the HTML file or in Your CSS

<style>
    @media print {
    * {
        -webkit-print-color-adjust: exact !important;
      }
    }
</style>
like image 22
Jeet Sapovadiya Avatar answered Oct 21 '25 20:10

Jeet Sapovadiya