使用 WKWebview 从 HTML 模板生成 PDF

问题描述 投票:0回答:0

我们现有的应用程序具有功能,必须生成 pdf,并且应该可以在 A4 纸上打印。 PDF差不多有8到10页

我已应用以下解决方案:

在WKwebview上加载HTML模板并对内容进行一些操作并将其转换为pdf。

  1. 将 HTML 转换为字符串
  2. 用动态内容替换一些数据

问题:

该解决方案在以前的操作系统(14.5、15.5、16.1)中运行良好,但不适用于最新的操作系统 16.6

表格背景 CSS 未渲染。我已经尝试过内联和外部 CSS 加载,但仍然面临同样的问题。

问题似乎出在 UIGraphics 或 WKwebview 格式化程序上。

您能帮我解决这个问题吗?

enter image description here

enter image description here

方法1:

func createPDF(formmatter: UIViewPrintFormatter, filename: String) -> String { let attributeString = NSAttributedString(string: "这是一个测试", 属性: [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

} }

方法2:

但是 pdf 是在单页而不是多页中生成的,并且无法使用以下解决方案进行打印。

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

/// 使用

webView.scrollView.frame
可以让我们捕获 // 整个页面,不仅仅是可见部分 pdfConfiguration.rect = CGRect(x: 0, y: 0, 宽度: webView.scrollView.contentSize.width, 高度: webView.scrollView.contentSize.height)

webView.createPDF(configuration: pdfConfiguration) { 结果 切换结果{ 案例.成功(让数据): // 创建下载目录的路径

    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)
}

} }

swift pdf wkwebview
© www.soinside.com 2019 - 2024. All rights reserved.