如何使用Cocoa(Mac)在Swift中创建PDF [英] How to create a PDF in Swift with Cocoa (Mac)
问题描述
Xcode 7.3.2,Swift 2,Cocoa(Mac)。
我的应用程序涉及用户输入一些文本,可以导出为PDF。
在我的应用程序的iOS版本中,我可以使用 CoreText
框架相对容易地创建PDF: p>
let html =< font face = \'Futura\'color = \SlateGray\> ; h2> \(title)< / h2>< / font>< font face = \Avenir\color = \SlateGray\>< h4& < / h4>< / font>
let fmt = UIMarkupTextPrintFormatter(markupText:html)
// 2.将打印格式化程序分配给UIPrintPageRenderer
let render = UIPrintPageRenderer $ b render.addPrintFormatter(fmt,startingAtPageAt:0)
// 3.分配paperRect和printableRect
让page = CGRect(x:10,y:10,width :595.2,height:841.8)// A4,72 dpi,从顶部和左边的10个边距。
let printable = page.insetBy(dx:0,dy:0)
render.setValue(NSValue(cgRect:page),forKey:paperRect)
render。 setValue(NSValue(cgRect:printable),forKey:printableRect)
//创建PDF上下文并绘制
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData,CGRect.zero,nil)
for i in 1 ... render.numberOfPages {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPage(at:i - 1,in:bounds)
}
UIGraphicsEndPDFContext
// 5.保存PDF文件
path =\(NSTemporaryDirectory())\(title).pdf
pdfData.write :path,atomically:true)
但是, UIMarkupTextPrintFormatter
, UIPrintPageRenderer
, UIGraphicsBeginPDFContextToData
和 UIGraphicsEndPDFContext
不存在于OS X.我如何做与我使用这个iOS代码(创建一个基本的PDF从一些HTML和写入到一个特定的文件路径作为分页的PDF)完全相同的事情与Mac和Cocoa? p>
EDIT:此问题的答案位于:创建分页的PDF-Mac OS X 。
这里是一个函数,将从纯HTML生成PDF。
func makePDF(markup:String){
let directoryURL = NSFileManager.defaultManager()。URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask)[0]
let printOpts:NSDictionary = [NSPrintJobDisposition:NSPrintSaveJob,NSPrintSaveJob:directoryURL]
let printInfo = NSPrintInfo(dictionary:printOpts as! [String:AnyObject])
printInfo.horizontalPagination = NSPrintingPaginationMode.AutoPagination
printInfo.verticalPagination = NSPrintingPaginationMode.AutoPagination
printInfo.topMargin = 20.0
printInfo.leftMargin = 20.0
printInfo.rightMargin = 20.0
printInfo.bottomMargin = 20.0
let view = NSView(frame:NSRect(x:0,y:0,width:570,height:740))
if let htmlData = markup.dataUsingEncoding(NSUTF8StringEncoding){
if let attrStr = NSAttributedString(HTML:htmlData,options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType],documentAttributes:nil){
let frameRect = NSRect(x:0,y:0,width:570,height:740)
let textField = NSTextField(frame:frameRect)
textField.attributedStringValue = attrStr
view.addSubview )
let printOperation = NSPrintOperation(view:view,printInfo:printInfo)
printOperation.showsPrintPanel = false
printOperation.showsProgressPanel = false
printOperation.runOperation b $ b}
}
}
发生了什么:
- 将HTML放入NSAttributedString。
- 将NSAttributedString复制到NSTextField。
- 将NSTextField呈现给NSView。
- 使用该NSView创建NSPrintOperation。
- 将打印参数设置为保存为PDF
- 运行打印操作(实际打开一个对话框保存PDF)
- 每个人都很高兴。
这不是一个完美的解决方案。请注意硬编码的整数值。
Xcode 7.3.2, Swift 2, Cocoa (Mac).
My app involves the user entering in some text, which can be exported to a PDF.
In the iOS version of my app, I can create the PDF relatively easily with the CoreText
framework:
let html = "<font face=\'Futura\' color=\"SlateGray\"><h2>\(title)</h2></font><font face=\"Avenir\" color=\"SlateGray\"><h4>\(string)</h4></font>"
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: 10, y: 10, width: 595.2, height: 841.8) // A4, 72 dpi, margin of 10 from top and left.
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, CGRect.zero, nil)
for i in 1...render.numberOfPages {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPage(at: i - 1, in: bounds)
}
UIGraphicsEndPDFContext();
// 5. Save PDF file
path = "\(NSTemporaryDirectory())\(title).pdf"
pdfData.write(toFile: path, atomically: true)
However, UIMarkupTextPrintFormatter
, UIPrintPageRenderer
, UIGraphicsBeginPDFContextToData
, and UIGraphicsEndPDFContext
all do not exist on OS X. How can I do the exact same thing as I am doing with this iOS code (create a basic PDF from some HTML and write it to a certain file path as a paginated PDF) with Mac and Cocoa?
EDIT: The answer to this question is here: Create a paginated PDF—Mac OS X.
Here is a function that will generate a PDF from pure HTML.
func makePDF(markup: String) {
let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let printOpts: NSDictionary = [NSPrintJobDisposition: NSPrintSaveJob, NSPrintSaveJob: directoryURL]
let printInfo = NSPrintInfo(dictionary: printOpts as! [String : AnyObject])
printInfo.horizontalPagination = NSPrintingPaginationMode.AutoPagination
printInfo.verticalPagination = NSPrintingPaginationMode.AutoPagination
printInfo.topMargin = 20.0
printInfo.leftMargin = 20.0
printInfo.rightMargin = 20.0
printInfo.bottomMargin = 20.0
let view = NSView(frame: NSRect(x: 0, y: 0, width: 570, height: 740))
if let htmlData = markup.dataUsingEncoding(NSUTF8StringEncoding) {
if let attrStr = NSAttributedString(HTML: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) {
let frameRect = NSRect(x: 0, y: 0, width: 570, height: 740)
let textField = NSTextField(frame: frameRect)
textField.attributedStringValue = attrStr
view.addSubview(textField)
let printOperation = NSPrintOperation(view: view, printInfo: printInfo)
printOperation.showsPrintPanel = false
printOperation.showsProgressPanel = false
printOperation.runOperation()
}
}
}
What is happening:
- Put the HTML into a NSAttributedString.
- Render the NSAttributedString to a NSTextField.
- Render the NSTextField to a NSView.
- Create a NSPrintOperation with that NSView.
- Set the printing parameters to save as a PDF.
- Run the print operation (which actually opens a dialog to save the PDF)
- Everyone is happy.
This is not a perfect solution. Note the hard coded integer values.
这篇关于如何使用Cocoa(Mac)在Swift中创建PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!