Rendering Annotations

PSPDFKit offers several options for rendering a single annotation object. This article serves as a step-by-step guide to get you started quickly.

ℹ️ Note: Before loading a document and rendering its annotations, you have to initialize PSPDFKit by providing your license. Make sure to follow the steps in our Adding the License Key guide before continuing with this guide, in order to have PSPDFKit fully initialized.

Loading a Document

The first step in rendering annotations of a PDF is to load the document in memory. The Document class offers a variety of methods for doing this. The following example loads a PDF document from the app’s Samples directory using Document(url:):

let samplesURL = Bundle.main.resourceURL?.appendingPathComponent("Samples")
let documentURL = samplesURL?.appendingPathComponent("document.pdf")
let document = Document(url: documentURL)
NSURL *samplesURL = [NSBundle.mainBundle.resourceURL URLByAppendingPathComponent:@"Samples"];
NSURL *documentURL = [samplesURL URLByAppendingPathComponent:@"document.pdf"];
PSPDFDocument *document = [[PSPDFDocument alloc] initWithURL:documentURL];

The complete list of available document initializers is provided in our PSPDFDocument Initialization API reference.

Retrieving Annotations

To retrieve all the annotations of your loaded Document instance, call Document.allAnnotations(of:). For example, you can retrieve all ink annotations from a document, like so:

// Retrieves all ink annotations of the document.
let annotations = document.allAnnotations(of: .all).values.flatMap { $0 }
// Retrieves all ink annotations of the document.
NSMutableArray<PSPDFAnnotation *> *inkAnnotations = [NSMutableArray<PSPDFAnnotation *> array];
for (NSArray<PSPDFAnnotation *> *annotations in [document allAnnotationsOfType:PSPDFAnnotationTypeInk].allValues) {
	[inkAnnotations addObjectsFromArray:annotations];

You can also query annotations from a specific page using Document.annotationsForPage(at:type:):

// Retrieves all ink annotations of a given page index of the loaded document.
let pageIndex = ...
let inkAnnotations = document.annotationsForPage(at: pageIndex, type: .ink)
// Retrieves all ink annotations of a given page index of the loaded document.
NSUInteger pageIndex = ...
NSMutableArray<PSPDFAnnotation *> *inkAnnotations = [document annotationsForPageAtIndex:pageIndex type:PSPDFAnnotationTypeInk];

💡 Tip: If you want to retrieve all of your document’s annotations at once, you can pass Annotation.Kind.all.

Rendering Annotations

You can render an annotation as a UIImage using Annotation.image(size:options:):

// Render annotation as a `UIImage`.
let renderedImage = annotation.image(with: CGSize(width: 200, height: 200), options: nil)
// Render annotation as a `UIImage`.
UIImage *renderedImage = [annotation imageWithSize:CGSizeMake(200.f, 200.f) options:nil];

ℹ️ Note: The bounding box is using PDF coordinates, which, unlike UIKit’s coordinates, are vertically flipped.