2

My goal is to write text on a PDF, like an annotation.

I achieved it transforming the PDFPage to a NSImage, I drew on the NSImage then I saved the PDF formed by the images.

let image = NSImage(size: pageImage.size)        
image.lockFocus()

let rect: NSRect = NSRect(x: 50, y: 50, width: 60, height: 20)
"Write it on the page!".draw(in: rect, withAttributes: someAttributes)

image.unlockFocus()

let out = PDFPage(image: image)

The problem is obviously that out (the new page of the output PDF) is a PDFPage of images and not a regular one. So the output PDF is very big in size and you can't copy and paste anything on it. It's just a sequence of images.

My question is if there's a way to add simple text on a PDF page programmatically without using NSImage. Any idea?

Note: There's this class in iOS programming UIGraphicsBeginPDFPageWithInfo which could be very helpful in my case. But I can't find the similar class for macOS development.

4
  • yeah... You can do this using html. Jun 19, 2017 at 21:16
  • @ClaudioCastro No other way? Here's how to solve my problem on iOS but I can't find an equivalent way in macOS: stackoverflow.com/questions/32113468/…
    – Matt
    Jun 19, 2017 at 21:23
  • I'm sorry, You talk about macOS... My solution was for iOS where I use html to generate a pdf with text and pictures. Jun 19, 2017 at 21:26
  • In new iOS 11 and xCode 9 there is some news about a pdf api. Jun 19, 2017 at 21:27

1 Answer 1

16

You can create a PDF graphics context on macOS and draw a PDFPage into it. Then you can draw more objects into the context using either Core Graphics or AppKit graphics.

Here's a test PDF I created by printing your question: input PDF

And here's the result from drawing that page into a PDF context, then drawing more text on top of it:

output PDF

Here's the code I wrote to transform the first PDF into the second PDF:

import Cocoa
import Quartz

let inUrl: URL = URL(fileURLWithPath: "/Users/mayoff/Desktop/test.pdf")
let outUrl: CFURL = URL(fileURLWithPath: "/Users/mayoff/Desktop/testout.pdf") as CFURL

let doc: PDFDocument = PDFDocument(url: inUrl)!
let page: PDFPage = doc.page(at: 0)!
var mediaBox: CGRect = page.bounds(for: .mediaBox)

let gc = CGContext(outUrl, mediaBox: &mediaBox, nil)!
let nsgc = NSGraphicsContext(cgContext: gc, flipped: false)
NSGraphicsContext.current = nsgc
gc.beginPDFPage(nil); do {
    page.draw(with: .mediaBox, to: gc)

    let style = NSMutableParagraphStyle()
    style.alignment = .center

    let richText = NSAttributedString(string: "Hello, world!", attributes: [
        NSFontAttributeName: NSFont.systemFont(ofSize: 64),
        NSForegroundColorAttributeName: NSColor.red,
        NSParagraphStyleAttributeName: style
        ])

    let richTextBounds = richText.size()
    let point = CGPoint(x: mediaBox.midX - richTextBounds.width / 2, y: mediaBox.midY - richTextBounds.height / 2)
    gc.saveGState(); do {
        gc.translateBy(x: point.x, y: point.y)
        gc.rotate(by: .pi / 5)
        richText.draw(at: .zero)
    }; gc.restoreGState()

}; gc.endPDFPage()
NSGraphicsContext.current = nil
gc.closePDF()
12
  • Perfect answer! I understand now.
    – Matt
    Jun 20, 2017 at 9:19
  • Hey Rob! What if I need to use the new drawn page? With your code, the new page gets saved at outUrl path but there's no way to access it programmatically. The only thing I could do is to save the PDFPage to outUrl and then open it again. I had a look on the documentation page of CGContext but I don't find anything to get the PDFPage which was modified. Any idea how to get it immediately after gc.closePDF() call? It isn't important, it was just for curiosity actually.
    – Matt
    Jun 20, 2017 at 16:04
  • 2
    Use the CGContext initializer that takes a CGDataConsumer argument. After you closePDF, you can create a new instance of PDFDocument from the data without going through a file.
    – rob mayoff
    Jun 20, 2017 at 16:45
  • This is a great answer, although I'm getting an error when trying to use NSGraphicsContext.setCurrent() in Swift 4. It says "Type 'NSGraphicsContext' has no member 'setCurrent'". It's still in the documentation so I'm not sure. Jan 30, 2018 at 21:13
  • NSGraphicsContext now has a property, current, instead of a setter method. I have updated my answer.
    – rob mayoff
    Jan 30, 2018 at 22:12

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.