使用的webview为WKWebView,核心部分代码(Swift 4):
// 创建打印渲染 let printPageRenderer:PDFRender = PDFRender() // 获取渲染格式 let viewFormatter:UIViewPrintFormatter = webView.viewPrintFormatter() // 设置渲染格式 printPageRenderer.addPrintFormatter(viewFormatter, startingAtPageAt: 0) // 将HTML渲染为PDF let pdfData:NSData = printPageRenderer.drawPDF() // 输出文件 let pdfFilename:String = "(NSHomeDirectory())/Documents/test.pdf" // 保存 pdfData.write(toFile: pdfFilename, atomically: true) // 获取文件的保存位置 let url = URL.init(fileURLWithPath: pdfFilename)
PDFRender类的实现
import UIKit class PDFRender: UIPrintPageRenderer { // A4纸大小 595*842 let pageFrame:CGRect = CGRect(x: 0.0, y: 0.0, 595, height: 842) override init() { super.init() // 设置打印纸的尺寸大小 self.setValue(pageFrame, forKey: "paperRect") // 设置内容区域大小 self.setValue(pageFrame, forKey: "printableRect") } /// 绘制PDF并生成NSData func drawPDF() -> NSData! { let data:NSMutableData = NSMutableData() // 小心!第二个参数如果设置为CGRect.zero,PDF尺寸就会是默认的 612*792 UIGraphicsBeginPDFContextToData(data, pageFrame, nil) self.prepare(forDrawingPages: NSRange.init(location: 0, length: self.numberOfPages)) let bounds:CGRect = pageFrame for i in 0..<self.numberOfPages{ UIGraphicsBeginPDFPage() self.drawPage(at: i, in: bounds) } UIGraphicsEndPDFContext() return data } }
Ficow原创,转载请注明出处:http://www.cnblogs.com/ficow/p/7859462.html