WKWebView详解--OC版
使用的webView
是WKWebView
,核心代码是Swift4.0
import UIKit
class PDFRender: UIPrintPageRenderer {
// A4纸大小 595*842
let pageFrame:CGRect = CGRect(x: 0.0, y: 0.0, width: 595.2, height: 841.8)
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
}
}
// 创建打印渲染
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)