如何在Swift中创建PDF

时间:2017-09-18 07:54:39

标签: html uiwebview swift2

我想使用UIWebView创建PDF。由于我有任何工作表细节,我想在Swift中保存生成PDF。我正在使用HTML格式的表格,但在第二页我的边框正在切割。

1 个答案:

答案 0 :(得分:2)

对于Swift 2我曾经使用过 字符串的html字符串(是用于表的确切html代码)! 然后

    let render = UIPrintPageRenderer()
    let fmt = UIMarkupTextPrintFormatter(markupText: html)

    render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)

    // 3. Assign paperRect and printableRect

    let page = CGRect(x: 0, y: 0, width: 612, height: 792) // some defaults
    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 pointzero = CGPoint(x: 0,y :0)
    let rect = CGRect.zero
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)

    for i in 0..<render.numberOfPages {
        UIGraphicsBeginPDFPage();
        render.drawPageAtIndex( i, inRect: UIGraphicsGetPDFContextBounds())
    }

    UIGraphicsEndPDFContext();

    // 5. Save PDF file
   let path = "\(NSTemporaryDirectory())sd.pdf"

    pdfData.writeToFile( path, atomically: true)
    print("open \(path)")