Adding Watermarks to PDFs on iOS

PSPDFKit enables you to draw a permanent watermark on all pages of a document. The example below shows how to generate a PDF with a watermark on all its pages using the Processor API:

// Create a default configuration.
let configuration = Processor.Configuration(document: document)!

configuration.drawOnAllCurrentPages { context, pageIndex, pageRect, renderOptions in
    // Careful. This code is executed on background threads. Only use thread-safe drawing methods.
    let text = "PSPDF Live Watermark On Page \(pageIndex + 1)"
    let stringDrawingContext = NSStringDrawingContext()
    stringDrawingContext.minimumScaleFactor = 0.1

    // Add text over the diagonal of the page.
    context.translateBy(x: 0, y: pageRect.size.height / 2)
    context.rotate(by: -.pi / 4)
    let attributes: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: 30),
        .foregroundColor: UIColor.red.withAlphaComponent(0.5)
    ]
    text.draw(with: pageRect, options: .usesLineFragmentOrigin, attributes: attributes, context: stringDrawingContext)
}

// Start the conversion from `document` to `processedDocumentURL`.
let processor = Processor(configuration: configuration, securityOptions: documentSecurityOptions)
try processor.write(toFileURL: processedDocumentURL)

The method above will write a new document to the URL pointed to by the processedDocumentURL argument. The resulting PDF file will have a permanent watermark on all of its pages, even when opened in other PDF editors.

Adding a Temporary Watermark

You can also add a temporary watermark as a rendering on the document pages without generating a new PDF. This temporary watermark isn’t a part of the document, and it won’t be saved to disk even if you call the document’s save method. Here’s how to add a temporary watermark:

let renderBlock: PSPDFRenderDrawBlock =  { context, pageIndex, pageRect, renderOptions in
    // Careful. This code is executed on background threads. Only use thread-safe drawing methods.
    let text = "PSPDF Live Watermark On Page \(pageIndex + 1)"
    let stringDrawingContext = NSStringDrawingContext()
    stringDrawingContext.minimumScaleFactor = 0.1

    // Add text over the diagonal of the page.
    context.translateBy(x: 0, y: pageRect.size.height / 2)
    context.rotate(by: -.pi / 4)
    let attributes: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: 30),
        .foregroundColor: UIColor.red.withAlphaComponent(0.5)
    ]
    text.draw(with: pageRect, options: .usesLineFragmentOrigin, attributes: attributes, context: stringDrawingContext)
}

document.updateRenderOptions(for: .page) {
    $0.drawBlock = renderBlock
}

For more details, see DrawOnPagesExample.swift from PSPDFKit Catalog.