Pdf使用UIViewPrintFormatter从Html创建,不显示本地图像

时间:2016-09-29 07:28:32

标签: html ios pdf uiwebview pdf-generation

我正在从带有images的html文件创建pdf。我尝试通过将html加载到Web视图中从Html和UIWebView创建。以下是两种方法的使用方法

1.从HTML

   func exportHTMLContentToPDF(HTMLContent: String) {
    let printPageRenderer = CustomPrintPageRenderer()

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

    let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer)

    pdfData.writeToFile(pdfPath(), atomically: true)

}

2.通过加载Html从UiWebView

func createPdfFromViewFormatter(viewFormatter:UIViewPrintFormatter) {

    let printPageRenderer = CustomPrintPageRenderer()

    printPageRenderer.addPrintFormatter(viewFormatter, startingAtPageAtIndex: 0)
    let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer)

    pdfData.writeToFile(pdfPath(), atomically: true)


}

Pdf创建方法`

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

    UIGraphicsBeginPDFContextToData(data, CGRect(x: 0.0, y: 0.0, width: printPageRenderer.printableRect.width, height: printPageRenderer.printableRect.height), nil)


    printPageRenderer.prepareForDrawingPages(NSRange(location: 0, length:printPageRenderer.numberOfPages() ))


    for i in 0..<printPageRenderer.numberOfPages() {


        UIGraphicsBeginPDFPage()

        printPageRenderer.drawPageAtIndex(i, inRect: UIGraphicsGetPDFContextBounds())

    }

    UIGraphicsEndPDFContext()


    return data
}

问题是html中的图像未显示在创建的pdf中。但是在UIWebView中加载时会显示它。

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题: IOS Swift sharing PDF documents with images 我相信这是一个错误。到目前为止我找到的唯一解决方案是创建一个隐藏的虚拟UIWebView。我在UIWebView中加载HTML,然后创建PDF。这是我的代码:

    override func viewDidLoad() {
    super.viewDidLoad()

    hiddenWebView.loadHTMLString(htmlText, baseURL: nil)
    hiddenWebView.isHidden = true
}

override func viewDidAppear(_ animated: Bool) {
    pdfDocument = getPdf()
    let tmpDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
    let fileURL = tmpDirectoryURL.appendingPathComponent("document.pdf")
    pdfDocument.write(to: fileURL, atomically: false)
    documentWebView.loadRequest(URLRequest(url: fileURL))
}

我希望它有所帮助。