Swift:将文件附件(不仅仅是图像)添加到PDF中

时间:2018-01-02 10:14:03

标签: swift pdf pdf-generation attachment

如何在Swift中使用" free"本地将其他文件附件添加到PDF中。库?我知道这可能是商业图书馆"快速pdf库"来自debenu.com。

今天我工作的Swift3代码看起来像这样,但不包括上面提到的文件附件功能:

// function PDF creation

func createPDFcontent(_ msgIDfunc: String) {

    self.doctitle = msgIDfunc
    self.author = "blabla"
    self.creator = "blabla"
    self.subject = msgIDfunc

    var infoDict = [String: AnyObject]()
    infoDict[kCGPDFContextTitle as String] = self.doctitle as NSString?
    infoDict[kCGPDFContextAuthor as String] = self.author as NSString?
    infoDict[kCGPDFContextCreator as String] = self.creator as NSString?
    infoDict[kCGPDFContextSubject as String] = self.subject as NSString?

    let HtmlForPDF = "<b><i><font color='red'>+++ Hello World +++</i></b></font>"

    // new hmtl version
    let frmt = UIMarkupTextPrintFormatter(markupText: HtmlForPDF)

    //  set print format

    let render = UIPrintPageRenderer()
    render.addPrintFormatter(frmt, startingAtPageAt: 0)

    //  create Paper Size for print

    let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8)
    let printable = page.insetBy(dx: 0, dy: 0)

    render.setValue(NSValue(cgRect: page), forKey: "paperRect")
    render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

    // create PDF context and draw

    let filedata = NSMutableData()
    UIGraphicsBeginPDFContextToData(filedata, CGRect.zero, infoDict)  

    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]

    filedata.write(toFile: "\(documentsPath)/blabla.pdf", atomically: true)

}

欢迎任何提示。

0 个答案:

没有答案