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

我有一个应用程序,可以查看已经存储在项目中的PDF。 我希望能够创build一个新的PDF文档,并将其存储在应用程序目录中,以便在现有的查看器中查看。 PDF将从数组var todoList: [String] = []显示在UITableView上创build。 我知道要创build一个PDF,我必须创build一个文件名,path和目录。 我不知道该怎么做 我看到了URL和URL请求的在线引用,但我不确定这是否是我想要的正确途径。 有人能给我一些build议和指导吗? 我能find的所有东西都是Objective-C。

我用这个代码来创build和保存文件(使用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, 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 documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] pdfData.writeToFile("\(documentsPath)/file.pdf", atomically: true) } 

然后我用这个代码从文档目录加载到UIWebView

 func loadPDF(filename: String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let filePath = "\(documentsPath)/\(filename).pdf" let url = NSURL(fileURLWithPath: filePath) let urlRequest = NSURLRequest(URL: url) webView.loadRequest(urlRequest) } 

对于Swift 3

 createPdf() { // 1. Create Print Formatter with input text. let formatter = UIMarkupTextPrintFormatter(markupText: textView.text) // 2. Add formatter with pageRender let render = UIPrintPageRenderer() render.addPrintFormatter(formatter, 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 rect = CGRect.zero let pdfData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfData, rect, 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)/new.pdf", atomically: true) print("saved success") }