在Swift中将图像添加到PDF文件

时间:2016-02-01 17:04:34

标签: swift image pdf

您好我正在尝试将图片视图中的图片添加到我的PDF文件中。

我已经在PDF中添加了文字,我只想添加图片。

到目前为止我得到了什么

@IBAction func CreatePDF(sender: AnyObject) {
    // 1. Create a print formatter

    let html = "<b>Hello <i>World!</i></b>"
    let fmt = UIMarkupTextPrintFormatter(markupText: html)

    // 2. Assign print formatter to UIPrintPageRenderer

    let render = UIPrintPageRenderer()
    render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)

    // 3. Assign paperRect and printableRect

    let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
    let printable = CGRectInset(page, 0, 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, CGRectZero, nil)

    for i in 1...render.numberOfPages() {

        UIGraphicsBeginPDFPage();
        let bounds = UIGraphicsGetPDFContextBounds()
        render.drawPageAtIndex(i - 1, inRect: bounds)
    }

    UIGraphicsEndPDFContext();

    // 5. Save PDF file

    let path = "\(NSTemporaryDirectory())file.pdf"
    pdfData.writeToFile(path, atomically: true)
    print("open \(path)") // command to open the generated file
}

0 个答案:

没有答案