Search PDF Annotations

With PSPDFKit For Web, it’s possible to get the list of all annotations for all pages and search for specific annotations.

To ensure the SDK doesn’t use too much memory on a user’s computer, annotations are loaded only when the page they’re on is navigated to by the user.

This means that to iterate though all the annotations, you’ll need to request them for each individual page. Here’s how that’s done:

const annotationsForEachPage = await Promise.all(
  Array.from(Array(instance.totalPageCount).keys()).map(instance.getAnnotations)
);

The function above gets all the annotations for each page in your document and returns an array of the list of all of the annotations for each page.

You can flatten it down so you have a single array of all of the annotations by calling flat:

const annotationsForEachPage = allAnnotations.flat();

Now that you have all the annotations, searching for a specific annotation is as simple as filtering the array to the annotation you need.

In this example, you’re searching for all empty text annotations:

const allEmptyTextAnnotations = allAnnotations.filter((annotation) => {
  return (
    annotation instanceof PSPDFKit.Annotations.TextAnnotation &&
    annotation.text.length === 0
  );
});