> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/web/get-started/samples/text-position.md).

# Text Position, Search and Highlight Sample Code

JavaScript to search & highlight text in PDF documents. Search for a string of text & set to case-sensitive. Found words are highlighted throughout the PDF.

{% hint style="info" %}
**Requirements**

*These packages are required to use these features in production. Trial keys have unlimited access to all features*

<a href="/web/get-started/readme.md" class="button primary">Web SDK</a><a href="https://showcase.apryse.com/pdf-search" class="button primary">Live demo</a>
{% endhint %}

This JavaScript sample lets you search and highlight text in PDF, DOCX, PPTX and XLSX documents by extracting text position (no servers or other external dependencies required). Users can search through a PDF for a whole word or look for case sensitive words. If a word is located in the document it is highlighted and the user can jump to the position of the word in the document.

This sample works on all browsers (including IE11) and mobile devices without using plug-ins. MS Office docs will require the [Office Conversion Package](https://apryse.com/capabilities#OfficeConversion).

Learn more about our [Web SDK](/web/get-started/guides.md).

{% tabs %}
{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
const viewerElement = document.getElementById('viewer');
// eslint-disable-next-line no-undef
const WebViewerConstructor = isWebComponent() ? WebViewer.WebComponent : WebViewer;

WebViewerConstructor(
  {
    path: '../../../lib',
    initialDoc: 'https://pdftron.s3.amazonaws.com/downloads/pl/legal-contract.pdf',
  },
  viewerElement
).then(instance => {
  samplesSetup(instance);
  const { documentViewer, annotationManager, Annotations } = instance.Core;

  const renderCheckBoxes = pageCount => {
    const pagesDiv = document.getElementById('pages');
    let pageNumber;
    const checkboxes = [];

    for (pageNumber = 1; pageNumber <= pageCount; pageNumber++) {
      const input = document.createElement('input');
      /* eslint-disable prefer-template */
      input.id = `page-${pageNumber}`;
      input.type = 'checkbox';
      input.checked = false;
      input.value = pageNumber;

      checkboxes.push(input);

      const label = document.createElement('label');
      label.htmlFor = `page-${pageNumber}`;
      label.innerHTML = `Page ${pageNumber}`;

      const lineBreak = document.createElement('br');

      pagesDiv.appendChild(input);
      pagesDiv.appendChild(label);
      pagesDiv.appendChild(lineBreak);
    }

    return checkboxes;
  };

  const highlightText = (searchText, pageNumber) => {
    const doc = documentViewer.getDocument();

    // gets all text on the requested page
    // see https://sdk.apryse.com/api/web/Core.Document.html#loadPageText__anchor
    doc.loadPageText(pageNumber).then(text => {
      let textStartIndex = 0;
      let textIndex;
      const annotationPromises = [];

      // find the position of the searched text and add text highlight annotation at that location
      while ((textIndex = text.indexOf(searchText, textStartIndex)) > -1) {
        textStartIndex = textIndex + searchText.length;
        // gets quads for each of the characters from start to end index. Then,
        // resolve the annotation and return.
        // see https://sdk.apryse.com/api/web/Core.Document.html#getTextPosition__anchor
        const annotationPromise = doc.getTextPosition(pageNumber, textIndex, textIndex + searchText.length).then(quads => {
          const annotation = new Annotations.TextHighlightAnnotation();
          annotation.Author = annotationManager.getCurrentUser();
          annotation.PageNumber = pageNumber;
          annotation.Quads = quads;
          annotation.StrokeColor = new Annotations.Color(0, 255, 255);
          return annotation;
        });
        annotationPromises.push(annotationPromise);
      }

      // Wait for all annotations to be resolved.
      Promise.all(annotationPromises).then(annotations => {
        annotationManager.addAnnotations(annotations);
        annotationManager.selectAnnotations(annotations);
      });
    });
  };

  const removeHighlightedText = pageNumber => {
    const annotations = annotationManager.getAnnotationsList().filter(annotation => {
      return annotation.PageNumber === pageNumber;
    });
    annotationManager.deleteAnnotations(annotations);
  };

  documentViewer.addEventListener('documentLoaded', () => {
    const textInput = document.getElementById('text');
    const checkboxes = renderCheckBoxes(documentViewer.getPageCount());

    checkboxes.forEach(checkbox => {
      checkbox.addEventListener('change', () => {
        const pageNumber = Number(checkbox.value);

        if (checkbox.checked && textInput.value) {
          highlightText(textInput.value, pageNumber);
        } else {
          removeHighlightedText(pageNumber);
        }
      });
    });

    textInput.addEventListener(
      'input',
      // debounce loaded elsewhere
      // eslint-disable-next-line
      debounce(() => {
        checkboxes.forEach(checkbox => {
          const pageNumber = Number(checkbox.value);

          if (checkbox.checked) {
            removeHighlightedText(pageNumber);

            if (textInput.value) {
              highlightText(textInput.value, pageNumber);
            }
          }
        });
      }, 200)
    );

    // highlight search text in the first page by default
    checkboxes[0].checked = true;
    highlightText(textInput.value, 1);
  });
});
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/web/get-started/samples/text-position.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
