0

我正在HtmltoPDF创作。当某些图像 URL 但不适用于我的服务器图像 URL 时,它工作正常。

从谷歌下载的工作网址
在此处输入图像描述

服务器图像 URL 中的问题

在此处输入图像描述

我在这里放了我的pdf生成代码。请找到它

func exportHTMLContentToPDF(HTMLContent: String) -> String {
        let printPageRenderer = IPPrintPageRenderer()

        let printFormatter = UIMarkupTextPrintFormatter(markupText: HTMLContent)
        printPageRenderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)

        let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer: printPageRenderer)
        let str = "\(Global.kretriveUserData().firstName!.firstCharacter!)\(Global.kretriveUserData().Name!.firstCharacter!)".uppercased()

        pdfFilename = "\(getDocDir())/\(str + invoiceNumber!).pdf"
        pdfData?.write(toFile: pdfFilename, atomically: true)

        print(pdfFilename)
        return pdfFilename
    }


    func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
        let data = NSMutableData()

        UIGraphicsBeginPDFContextToData(data, CGRect.zero, nil)
        for i in 0..<printPageRenderer.numberOfPages {
            UIGraphicsBeginPDFPage()
            printPageRenderer.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())
        }
        UIGraphicsEndPDFContext()
        return data
    }

    func getDocDir() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    }

您可以在此处找到完整的演示。

谢谢,

4

1 回答 1

2

要从 webView 生成 pdf,您需要准备 HTML 代码,创建 WebView 并在 webView 中注入 HTML 代码,然后在 webViewdidFinishLoading中使用与 webView 相同的宽度和高度打印 pdf 中的 HTML 内容。

func webViewDidFinishLoad(_ webView: UIWebView) {

    let render = UIPrintPageRenderer()
    render.addPrintFormatter(webView.viewPrintFormatter(), startingAtPageAt: 0);


    let page = CGRect(x: 0, y: 10, width: webView.frame.size.width, height: webView.frame.size.height) // take the size of the webView
    let printable = page.insetBy(dx: 0, dy: 0)
    render.setValue(NSValue(cgRect: page), forKey: "paperRect")
    render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

    // 4. Create PDF context and draw
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
    for i in 1...render.numberOfPages {

        UIGraphicsBeginPDFPage();
        let bounds = UIGraphicsGetPDFContextBounds()
        render.drawPage(at: i - 1, in: bounds)
    }
    UIGraphicsEndPDFContext();
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

    print(documentsPath)

    pdfData.write(toFile: "\(documentsPath)/pdfName.pdf", atomically: true)

    self.pdfPath = "\(documentsPath)/pdfName.pdf"
    self.pdfTitle = "pdfName"
    self.performSegue(withIdentifier: "showPDFSegue", sender: nil)
    webView.removeFromSuperview()
    self.loadingScreenViewController.view.removeFromSuperview()
}

快乐编码:)

于 2019-07-22T05:43:09.837 回答