How to create a PDF in Swift with Cocoa (Mac)

后端 未结 1 360
Happy的楠姐
Happy的楠姐 2020-12-09 00:49

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 creat

1条回答
  •  借酒劲吻你
    2020-12-09 01:19

    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: [NSPrintInfo.AttributeKey: Any] = [NSPrintInfo.AttributeKey.jobDisposition: NSPrintInfo.JobDisposition.save, NSPrintInfo.AttributeKey.jobSavingURL: directoryURL]
        let printInfo = NSPrintInfo(dictionary: printOpts)
        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.run()
            }
        }
    }
    

    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.

    0 讨论(0)
提交回复
热议问题