如何使用Cocoa(Mac)在Swift中创建PDF [英] How to create a PDF in Swift with Cocoa (Mac)

查看:535
本文介绍了如何使用Cocoa(Mac)在Swift中创建PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.horizo​​ntalPagination = 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}
}
}

发生了什么:


  1. 将HTML放入NSAttributedString。

  2. 将NSAttributedString复制到NSTextField。

  3. 将NSTextField呈现给NSView。

  4. 使用该NSView创建NSPrintOperation。

  5. 将打印参数设置为保存为PDF

  6. 运行打印操作(实际打开一个对话框保存PDF)

  7. 每个人都很高兴。

这不是一个完美的解决方案。请注意硬编码的整数值。


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:

  1. Put the HTML into a NSAttributedString.
  2. Render the NSAttributedString to a NSTextField.
  3. Render the NSTextField to a NSView.
  4. Create a NSPrintOperation with that NSView.
  5. Set the printing parameters to save as a PDF.
  6. Run the print operation (which actually opens a dialog to save the PDF)
  7. Everyone is happy.

This is not a perfect solution. Note the hard coded integer values.

这篇关于如何使用Cocoa(Mac)在Swift中创建PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆