Swift version: 5.10
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:
PDFPage
.import PDFKit
to the top of the new file.PDFView
and make the ViewController
class conform to the PDFDocumentDelegate
protocol.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.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:
super.draw()
, your content will appear behind the page content. That might be what you want, but we’ll be doing the opposite here.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:
override func draw(with box: PDFDisplayBox, to context: CGContext) {
super.draw(with: box, to: context)
let string: NSString = "FREE SAMPLE"
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.red, .font: UIFont.boldSystemFont(ofSize: 32)]
let stringSize = string.size(withAttributes: attributes)
UIGraphicsPushContext(context)
context.saveGState()
let pageBounds = bounds(for: box)
context.translateBy(x: (pageBounds.size.width - stringSize.width) / 2, y: pageBounds.size.height)
context.scaleBy(x: 1.0, y: -1.0)
string.draw(at: CGPoint(x: 0, y: 55), withAttributes: attributes)
context.restoreGState()
UIGraphicsPopContext()
}
If everything went well you should now see “FREE SAMPLE” emblazoned across every page of your PDF.
SPONSORED Transform your career with the iOS Lead Essentials. This Black Friday, unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a free crash course.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS – learn more in my book Advanced iOS: Volume Two
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.