iOS UIPrintPageRenderer打印每个要打印的页面的最后一页

时间:2017-07-17 14:15:03

标签: ios swift uiprintpagerenderer

我正在开发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只包含多次打印的最后一页(对于页面中的每个页面一次,这不是预期的行为。

0 个答案:

没有答案