How to annotate text when receiving text as a string in pdf?

PDF.js Express Version

Detailed description of issue
We are getting text as a string from backend and we need to search that in our pdf and highlight it with a red box. Is that possible with pdf js express?

Expected behaviour
HIghlighting text with red box on receiving array with text string from backend.

Link to document
{Provide a link to the document in question if possible}

Code snippet
{Provide a relevant code snippet}

Hi there,

instance.searchText() lets you search for strings and automatically highlights the results for you.

You can also change the color of the highlights (see code below).

WebViewer(...).then(instance => {
   const {docViewer} = instance;

    docViewer.on('documentLoaded', () => {
         searchResult: new Annotations.Color(0, 0, 255, 0.5),
         activeSearchResult: 'rgba(0, 255, 0, 0.5)'

       instance.searchText('your text here')

We do have other more advanced search APIs if you need more flexibility, so if this solution doesn’t work for you let me know and I can help you out with those.


Hi Logan,
Thanks for the solution. Is there any way to create a outline box around the searched word instead of a highlight color?


This gets into the more complex APIs that I was talking about. Here is a code sample doing what you want:

  const { annotManager, Annotations, Tools, docViewer, CoreControls } = instance;

  docViewer.on('documentLoaded', () => {

    const mode = CoreControls.Search.Mode.PAGE_STOP | CoreControls.Search.Mode.HIGHLIGHT;

    const searchOptions = {
      // If true, a search of the entire document will be performed. Otherwise, a single search will be performed.
      fullSearch: true,
      // The callback function that is called when the search returns a result.
      onResult: result => {
        // with 'PAGE_STOP' mode, the callback is invoked after each page has been searched.
        if (result.resultCode === CoreControls.Search.ResultCode.FOUND) {
          const textQuad = result.quads[0].getPoints(); // getPoints will return Quad objects

          const annot = new Annotations.RectangleAnnotation();
          annot.StrokeColor = new Annotations.Color(255, 0, 0, 1);
          annot.X = textQuad.x1;
          annot.Y = textQuad.y3;
          annot.Width = textQuad.x2 - textQuad.x1
          annot.Height = textQuad.y1 - textQuad.y3


    docViewer.textSearchInit('YOUR_TEXT', mode, searchOptions);


API references can be found here.


Thanks Logan . This was really helpful!

1 Like