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.

18
  • 3
    See developer.apple.com/library/mac/documentation/GraphicsImaging/…, "Creating a PDF file" as a starting point. You can make a NSAttributedString out of HTML and draw that.
    – zneak
    Aug 15, 2016 at 0:21
  • Not in front of my computer, but you'll want to look up how you can set a CGContextRef in a NSGraphicsContext and then you'll be able to use NSAttributedString's draw methods.
    – zneak
    Aug 15, 2016 at 2:52
  • You're welcome to edit your question if you run into more specific issues. I'm on a Windows machine at work, though.
    – zneak
    Aug 15, 2016 at 6:19
  • @zneak I'm having trouble converting all that Objective-C to Swift, I keep getting the error "Could not convert CG[whatever] to UnsafePointer<void>"
    – John Ramos
    Aug 15, 2016 at 12:22
  • With what method call?
    – zneak
    Aug 15, 2016 at 14:59

1 Answer 1

6

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.

6
  • Thank you very much for your answer, it's really very close! Unfortunately, it only generates one page, and overflow text gets cut off. How can I get the text to go onto a new page?
    – John Ramos
    Aug 23, 2016 at 23:59
  • maybe we'd have to do some JavaScript on the HTML to determine page height ... idk if the pixel height scales the same for the HTML as the PDF every time or not
    – quemeful
    Aug 24, 2016 at 0:13
  • Huh. There's no easy way to paginate the thing? This code gist lets me do the HTML->PDF thing on iOS with easy automatic pagination, is there a way we can adapt the pagination part of that iOS code to something that'll work on OS X?
    – John Ramos
    Aug 24, 2016 at 15:35
  • quemeful, I've started a bounty on this question. If you can give me advice on how to paginate the PDF I create (instead of it getting cut off like in your code, it should go onto a new page!), I will happily award you some internet points.
    – John Ramos
    Sep 11, 2016 at 1:23
  • How to save it in a specified folder and without a dialog ? thx Oct 16, 2016 at 22:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.