使用Swift for iOS以编程方式创建和存储PDF文档

使用Swift for iOS以编程方式创建和存储PDF文档,第1张

使用Swift for iOS以编程方式创建和存储PDF文档

我使用此代码创建和保存文件(使用HTML)

func createPDF() {    let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"    let fmt = UIMarkupTextPrintFormatter(markupText: html)    // 2. Assign print formatter to UIPrintPageRenderer    let render = UIPrintPageRenderer()    render.addPrintFormatter(fmt, startingAtPageAt: 0)    // 3. Assign paperRect and printableRect    let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi    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, .zero, nil)    for i in 1...render.numberOfPages {        UIGraphicsBeginPDFPage();        let bounds = UIGraphicsGetPDFContextBounds()        render.drawPage(at: i - 1, in: bounds)    }    UIGraphicsEndPDFContext();    // 5. Save PDF file    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]    pdfData.write(toFile: "(documentsPath)/file.pdf", atomically: true)}

然后,

UIWebView
使用以下代码将其从documents目录加载到其中:

func loadPDF(filename: String) {    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]    let url = URL(fileURLWithPath: documentsPath, isDirectory: true).appendingPathComponent(filename).appendingPathExtension("pdf")    let urlRequest = URLRequest(url: url)    webView.loadRequest(urlRequest)}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5622484.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存