Highlight custom search results

Q: How can I implement custom search and then highlight the results programmatically?

A: This can be achieved by implementing the following functionalities:

  • search the whole PDF or a range of pages using the instance.search API.
  • Create highlight annotations on all the search results using instance.create.

The code for this will look like:

Copy
1
2
3
4
5
6
7
8
9
10
const results = await instance.search("hello");

const annotations = results.map(result => {
  return new PSPDFKit.Annotations.HighlightAnnotation({
    pageIndex: result.pageIndex,
    rects: result.rectsOnPage,
    boundingBox: PSPDFKit.Geometry.Rect.union(result.rectsOnPage)
  });
});
instance.create(annotations);

This has been tested with PSPDFKit for Web 2019.5.3