How to watermark PDFs inside a PDFView

PDFKit makes it easy to watermark PDFs as they are rendered, for example to add “FREE SAMPLE” over pages. It takes six steps, five of which are trivial and one which involves a little Core Graphics heavy lifting.

Let’s get the easy stuff out of the way:

Create a new Cocoa Touch Class called “SampleWatermark”, making it a subclass of PDFPage.

Add import PDFKit to the top of the new file.

Open whichever view controller owns your PDFView and make the ViewController class conform to the PDFDocumentDelegate protocol.

Find the code where you load your document (something like pdfView.document = document) then insert this directly before: document.delegate = self. That means the document will ask your view controller what class it should use to render pages.

Finally, we need to add a new method to the view controller to tell it to use the SampleWatermark class for its pages.

Add this method to your view controller now:

func classForPage() -> AnyClass {
return SampleWatermark.self
}

What we’ve just done is create a new PDFPage subclass that will handle watermark rendering, then tell our PDFDocument to use it for all pages. We haven’t given the SampleWatermark class any code yet, which means it will look just like a regular page – we’re going to fix that now.

When doing custom PDF rendering there are a few things to know:

If you draw your content before calling super.draw(), your content will appear behind the page content. That might be what you want, but we’ll be doing the opposite here.

You’re given a graphics context to draw into, but you should tread carefully: save the context and its state before you make any changes, then restore them afterwards.

PDFs have a variety of drawing boxes that determine how things are displayed. We don’t care which one is used, but we do need to ask PDFKit to tell us the page bounds for that box so we know how to position our text.

UIKit and PDFs draw in different directions, but you can correct that by moving the drawing position down by the height of the document then flipping its Y axis.

We’re going to write the words “FREE SAMPLE” in red, centered near the top of each page using a bold font. Add this method to SampleWatermark.swift:

If everything went well you should now see “FREE SAMPLE” emblazoned across every page of your PDF.

Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!