Watermark PDF Using PDFKit in Swift

Darwin Harianto
4 min readMay 22, 2019

--

PDF is one of the most used file format for viewing documents. When we are viewing pdf file, sometimes we are in a situation where we want to edit a pdf file. A few days ago, I tried to edit a plain pdf file. To my surprise, there is not a lot of pdf editing tutorial on iOS. There is another article on medium that already discussed how to make annotations. So in this one, I will try to give a watermark. My source code is from the apple documentation on watermark.

In this tutorial I plan to cover:

  1. Load PDF to view
  2. Add watermark
  3. Save pdf file

I will keep this as simple as I can.

If you have downloaded the source code, we can start by running our code.

Running the code, will already gives us an error. Yikes!!

Error on run

To resolve this, we simple need to change our ViewController.swift.

from

to

And everything will run normally. Not really a pleasant experience. Despite downloading from apple docs.

Now we can see our fully functioning code.

Now we can start dissecting the code.

Main.storyboard

View is composed with a single UIView with PDFView class. In this view we can later read our sample.pdf file.

ViewController.swift

Going to ViewController.swift, at line 33~44, this method call Sample.pdf, put it inside our PDFView (our view inside Main.storyboard), and set our pdf as a delegate.

Setting a view as delegate, enables us to call PDFKit functions. This allows us to interact with our PDF.

PDFView delegate

This delegate make our pdf pages to conforms with our WatermarkPage settings.

So, what is our WatermarkPage?

WatermarkPage.swift

Our WatermarkPage is set to draw a string ('U s e r 3 1 4 1 5 9') with a little tilt.

From here onward, suppose we want to add a new 'Hello PDFKIT' at the top left side of PDF page. we can do that by adding

right under line 46.

If you rebuild and run the code, it will looks like this.

For a custom color and size or position, it all can be adjusted by playing with stringAttributes or CGPoint inside draw method.

This draw step can be used to put images too. I will leave that for you guys as a homework. :D

For the last step. Saving the pdf after we are done with it is pretty simple.

We just need to put

Then call saveFile() just inside our ViewDidAppear() method. Just before the closing bracket.

After you rebuild and rerun the code, our file location will be printed on debug

File Location

Following that path, we can locate our save file location.

Hope this helps. cheers !!

--

--