我正在开发一个 iOS 应用程序,我想以 PDF 格式导出某些报告。所以我正在使用 webView 生成报告并将 webView 打印为 pdf。
这是我的代码:
var renderer : UIPrintPageRenderer!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
renderer = CustomPrintPageRenderer()
if let url = Bundle.main.url(forResource: "pdf", withExtension: "html", subdirectory: "web") {
let request = URLRequest(url: url);
webView.delegate = self;
webView.loadRequest(request);
}
}
func webViewDidFinishLoad(_ webView: UIWebView) {
var pages : [UIViewPrintFormatter] = []
var index = 0
for query in queryList {
var result = webView.stringByEvaluatingJavaScript(from: query)
if(!webView.isLoading) {
let printFormatter = webView.viewPrintFormatter()
pages.append(printFormatter)
}
}
for page in pages {
renderer.addPrintFormatter(page, startingAtPageAt: index)
index = index + 1
}
let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer: renderer)
pdfData?.write(toFile: "\(AppDelegate.getAppDelegate().getDocDir())/report.pdf", atomically: true)
}
func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
let data = NSMutableData()
UIGraphicsBeginPDFContextToData(data, CGRect.zero, nil)
printPageRenderer.prepare(forDrawingPages: NSMakeRange(0, printPageRenderer.numberOfPages))
let bounds = UIGraphicsGetPDFContextBounds()
for i in 0...(printPageRenderer.numberOfPages - 1) {
UIGraphicsBeginPDFPage()
printPageRenderer.drawPage(at: i, in: bounds)
}
UIGraphicsEndPDFContext();
return data
}
现在的问题是,生成的 PDF 仅包含多次打印的最后一页(页面中的每一页一次,这不是预期的行为。