JasonK
JasonK

Reputation: 65

How to make PDF annotations part of the file in Swift and PDFKit?

I am adding a watermark to the first page of a pdf using annotations in swift. The issue is that in the iOS print sheet the "Show annotations" toggle now pops up. If the user turns that off the watermark will not show on the printed pdf. Is there a way to make the annotation part of the pdf vector file so that the user cannot remove it? Or should I go about this watermarking in a different way?

Here is the function I am using:

func addWatermark(document: PDFDocument, numberOfPrints: Int, date: Date) -> PDFDocument {
        let page = document.page(at: 0)!
        let bounds = page.bounds(for: .cropBox)
        let copiesText: String = (numberOfPrints > 1 ? "copies" : "copy")
        let annotation = PDFAnnotation(bounds: CGRect(x: (bounds.size.width / 2) - 125, y: 3, width: 250, height: 20), forType: .freeText, withProperties: nil)
        annotation.alignment = .center
        annotation.contents = "Printed \(date.formatted(date: .numeric, time: .omitted)), \(numberOfPrints) \(copiesText)."
        annotation.font = UIFont(name: "RobotoSlab-Light", size: 8)!
        annotation.fontColor = .black
        annotation.color = .clear
        annotation.shouldPrint = true
        page.addAnnotation(annotation)
        return document
    }

I am then sending the returned pdf to the iOS print sheet:

func printPage(_ document: PDFDocument) {

    let printInfo = UIPrintInfo(dictionary:nil)
    printInfo.jobName = "title"
    printInfo.outputType = .general
    
    let printController = UIPrintInteractionController.shared
    printController.printInfo = printInfo
    
    printController.printingItem = document.dataRepresentation()
    
    printController.present(animated: true) { (controller, success, error) -> Void in
        dismiss()
    }
}

Upvotes: 0

Views: 69

Answers (0)

Related Questions