使用 Swift for iOS 以编程方式创建和存储 PDF 文档 [英] Create and store PDF document programmatically using Swift for iOS
问题描述
我有一个应用程序可以查看已存储在项目中的 PDF.我希望能够创建一个新的 PDF 文档并将其存储在应用程序目录中,以便以后在现有查看器中查看.PDF 将从显示在 UITableView
上的数组 var todoList: [String] = []
创建.我知道要创建 PDF,我必须创建文件名、路径和目录.我不知道该怎么做.我看到了对 URL 和 URL 请求的在线参考,但我不确定这是否是我想要做的正确途径.有人可以给我一些建议和指导吗?我能找到的所有东西都是针对 Objective-C 的.
I have an app that can view a PDF that is already stored within the project. I want to be able to create a new PDF document and store it in the app directory to later view in the already existing viewer. The PDF would be created from an array var todoList: [String] = []
that is displayed on a UITableView
. I know to create a PDF, I have to create a file name, path, and directory. I don't know how to do this. I saw online reference to URL and URL request, but I'm not sure if this is the correct avenue for what I want to do. Can someone please give me some advice and guidance? Everything I can find is for Objective-C.
推荐答案
我用这段代码来创建和保存文件(使用 HTML)
I used this code to create and save the file (using 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
中:
Then I loaded it into UIWebView
from the documents directory with this code:
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)
}
这篇关于使用 Swift for iOS 以编程方式创建和存储 PDF 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!