使用图像在WKWebView中从HTML生成PDF

时间:2018-04-13 20:38:49

标签: ios swift xcode pdf wkwebview

我试图在我的应用中生成发票PDF。我们的想法是可以打印发票,然后生成PDF以便稍后通过电子邮件发送。

一切正常,包括打印格式,但当我导出为PDF时,PDF中的徽标图像消失。

这是我在WKWebView中的原始HTML

enter image description here 这是我的可打印版本

但是当我导出到PDF时它看起来像这样: enter image description here 徽标遗失。

我的HTML是这样的:

        <tr>
            <td>
                <table class="headerTable">
                    <tr>
                        <td width="33%"><img src="logo.png" style="width:80%; max-width:250px"></td>
                        <td width="1%"></td>
                        <td width="33%"><b>Realengo</b><br>Avenida Santa Cruz 1251<br>Realengo - Rio de Janeiro<br>Telefone: (21) 2401-0271</td>
                        <td width="33%"><b>Centro</b><br>Rua Buenos Aires 111<br>Centro - Rio de Janeiro<br>Telefone: (21) 2151-1189</td>
                    </tr>
                </table>
            </td>
        </tr>

有没有人弄清楚为什么我的图片不是PDF?

1 个答案:

答案 0 :(得分:2)

迅捷4.2 信用:http://www.swiftdevcenter.com/create-pdf-from-uiview-wkwebview-and-uitableview/

extension WKWebView {

// Call this function when WKWebView finish loading
 func exportAsPdfFromWebView() -> String {
    let pdfData = createPdfFile(printFormatter: self.viewPrintFormatter())
    return self.saveWebViewPdf(data: pdfData)
 }

 func createPdfFile(printFormatter: UIViewPrintFormatter) -> NSMutableData {

    let originalBounds = self.bounds
    self.bounds = CGRect(x: originalBounds.origin.x, y: bounds.origin.y, width: self.bounds.size.width, height: self.scrollView.contentSize.height)
    let pdfPageFrame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.scrollView.contentSize.height)
    let printPageRenderer = UIPrintPageRenderer()
    printPageRenderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)
    printPageRenderer.setValue(NSValue(cgRect: UIScreen.main.bounds), forKey: "paperRect")
    printPageRenderer.setValue(NSValue(cgRect: pdfPageFrame), forKey: "printableRect")
    self.bounds = originalBounds
    return printPageRenderer.generatePdfData()
 }

 // Save pdf file in document directory
 func saveWebViewPdf(data: NSMutableData) -> String {

    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let docDirectoryPath = paths[0]
    let pdfPath = docDirectoryPath.appendingPathComponent("webViewPdf.pdf")
    if data.write(to: pdfPath, atomically: true) {
        return pdfPath.path
    } else {
        return ""
    }
  }
}

extension UIPrintPageRenderer {

 func generatePdfData() -> NSMutableData {
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, self.paperRect, nil)
    self.prepare(forDrawingPages: NSMakeRange(0, self.numberOfPages))
    let printRect = UIGraphicsGetPDFContextBounds()
    for pdfPage in 0..< self.numberOfPages {
        UIGraphicsBeginPDFPage()
        self.drawPage(at: pdfPage, in: printRect)
    }
    UIGraphicsEndPDFContext();
    return pdfData
 }
}