使用Swift for iOS以编程方式创建和存储PDF文档 [英] Create and store PDF document programmatically using Swift for iOS
问题描述
我有一个可以查看已存储在项目中的PDF的应用。我希望能够创建一个新的PDF文档并将其存储在app目录中,以便稍后在现有的查看器中查看。 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屋!