Zoom to a specific annotation when the PDF loads

Q: When a PDF loads in PSPDFKit, we want to zoom in to a particular annotation.

A: You can zoom to an annotation by passing the annotation’s bounding box to the zoom(toPDFRect:forPageAt:animated:) method of PDFDocumentViewController.

Copy
1
2
3
4
5
6
7
8
9
10
11
12
class CustomPDFViewController: PDFViewController {
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        // Find the first annotation for demonstration purposes.
        guard let document = self.document, let annotation = document.annotationsForPage(at: 0, type: .all).first else {
            return
        }

        self.documentViewController?.zoom(toPDFRect: annotation.boundingBox, forPageAt: 0, animated: true)
    }
}
Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@interface CustomPDFViewController : PSPDFViewController
@end

@implementation CustomPDFViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // Find the first annotation for demonstration purposes.
    PSPDFAnnotation *annotation = [[self.document annotationsForPageAtIndex:0 type:PSPDFAnnotationTypeAll] firstObject];

    if (!annotation) {
        return;
    }

    [self.documentViewController zoomToPDFRect:annotation.boundingBox forPageAtIndex:0 animated:YES];
}

@end

This has been tested with PSPDFKit 8.4 for iOS.