The Annotation Object Model

This article explains how the PSPDFAnnotation and PSPDFFormElement classes can be used. For an overview of annotation support in PSPDFKit, see the Introduction to Annotations guide.

To learn more about how you can check if annotations have been added/removed/changed, see the Detecting If Annotations Have Changed guide.

Changing Annotations

The annotation object model is based on PSPDFModel. Changes need to be made on the main thread. If a PSPDFViewController is currently displaying the PSPDFDocument that owns the annotation, you should emit a change notification to ensure the UI is correctly updated:

Copy
1
2
3
4
let freeTextAnnotation: PSPDFFreeTextAnnotation = ...
freeTextAnnotation.contents = "These are my new note contents."

NotificationCenter.default.post(name: NSNotification.Name.PSPDFAnnotationChanged, object: freeTextAnnotation, userInfo: [PSPDFAnnotationChangedNotificationKeyPathKey: ["contents"]])
Copy
1
2
3
4
5
PSPDFFreeTextAnnotation *freeTextAnnotation = ...;
freeTextAnnotation.contents = @"These are my new note contents.";

[NSNotificationCenter.defaultCenter postNotificationName:PSPDFAnnotationChangedNotification
object:freeTextAnnotation userInfo:@{PSPDFAnnotationChangedNotificationKeyPathKey : @[@"contents"]}];

This sends a PSPDFAnnotationChangedNotification. The PSPDFAnnotationChangedNotificationKeyPathKey should match the change you’ve made, as this enables PSPDFKit to perform additional performance optimizations (for example, various properties might not require a new render step).

Adding Annotations

Annotations can be added by calling addAnnotations:options: on your PSPDFDocument. This will emit a PSPDFAnnotationsAddedNotification.

Deleting Annotations

Deleting annotations should be performed by calling removeAnnotations:options: on your PSPDFDocument. This will emit either PSPDFAnnotationsRemovedNotification or PSPDFAnnotationChangedNotification, depending on whether or not the annotation has already been saved in the PDF. If it has been saved, we need to use soft delete to track and correctly update the file.

Thread Safety

Annotations should only be accessed on the main thread. They can be created and configured on any thread, but as soon as they’re added to a PSPDFDocument, they may only be modified on the main thread. Violating this convention can lead to crashes, data corruption, and deadlock.

💡 Tip: You can also access annotations when tapping on them by implementing PSPDFViewControllerDelegate methods like -pdfViewController:didTapOnAnnotation:annotationPoint:annotationView:pageView:viewPoint:.