> 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/webviewer-server-side-search.md).

# Enhanced Server-Side Search Functionality

Sample project to integrate WebViewer with Node.js enabling server-side searches.

This sample integrates WebViewer into a Node.js project, enabling a server-side search feature that replaces the default client-side search.

WebViewer provides a slick out-of-the-box responsive UI that enables you to view, annotate and manipulate PDFs and other document types inside any web project.

Once you generate your license key, it will automatically be included in your sample code below.

{% @apryse-license-key/apryse-license-key platform="WEB\_VIEWER" variant="compact" %}

Click the button below to view the full project in GitHub.

{% tabs %}
{% tab title="index.js" %}

<pre class="language-js" data-line-numbers><code class="lang-js">if(!fetch || !Promise){
  // check if browser supports fetch and Promises
  const viewerElement = document.getElementById('viewer');
  viewerElement.innerHTML = 'This example requires browser supporting both fetch and Promise API. Internet Explorer 11 not supported.'
}

function requestSearch(keyword, options){
  const apiUrl = new URL('http://localhost:8080/api/search');
  // add keyword as a url query parameter
  apiUrl.searchParams.append("keyword", keyword);
  const optionKeys = Object.keys(options);
  // Add all search options as a url query parameters
  optionKeys.forEach(function(key){
    apiUrl.searchParams.append(key, options[key]);
  });
  return fetch(apiUrl.href)
    .then(function(response){
      if(response.ok){
        return response.json();
      } else {
        console.log('Backend call failed, ', response.statusText);
      }
    });
}

function convertQuadCoordinatesToPdfCoordinates(document, pageNumber, quad){
  // PDFNet search result coordinate space is different than WebViewer coordinate space
  // so we need to convert them to be able to show highlights correctly
  // https://docs.apryse.com/documentation/web/guides/coordinates/
  const point1 = document.getPDFCoordinates(pageNumber, quad.p1x, quad.p1y);
  const point2 = document.getPDFCoordinates(pageNumber, quad.p2x, quad.p2y);
  const point3 = document.getPDFCoordinates(pageNumber, quad.p3x, quad.p3y);
  const point4 = document.getPDFCoordinates(pageNumber, quad.p4x, quad.p4y);
  return {
    'x1': point1.x,
    'y1': point1.y,
    'x2': point2.x,
    'y2': point2.y,
    'x3': point3.x,
    'y3': point3.y,
    'x4': point4.x,
    'y4': point4.y,
  }
}

function convertSearchResultForWebViewer(document, result){
  const webViewerFormattedQuads = result.quads.map((quad) => {
    // PDFNet search result coordinate space is different than WebViewer coordinate space
    // so we need to convert them to be able to show highlights correctly
    // https://docs.apryse.com/documentation/web/guides/coordinates/
    return convertQuadCoordinatesToPdfCoordinates(document, result.page_num, quad);
  });
  // WebViewer uses slightly modified result format than PDFNet on the server side.
  // To support displaying results on default UI, we need to convert it to match WebViewer format
  const searchResult = {
    resultCode: result.code,
    resultStr: result.out_str,
    resultStrStart: -1,
    resultStrEnd: -1,
    result_str: result.out_str,
    result_str_start: -1,
    result_str_end: -1,
    page_num: result.page_num,
    pageNum: result.page_num,
    ambient_str: result.ambient_str,
    ambientStr: result.ambient_str,
    quads: webViewerFormattedQuads
  };
  return searchResult;
}

function executeSearchOnBackendFactory(docViewer){
  // Function that will be executed instead of default search
  return function executeSearchOnBackend(searchValue, searchOptions){
    docViewer.clearSearchResults();
    const document = docViewer.getDocument();
    requestSearch(searchValue, searchOptions).then((data) => {
      if(data &#x26;&#x26; data.length > 0) {
        const extendedResult = data.map((result) => {
          return convertSearchResultForWebViewer(document, result);
        });
        docViewer.displayAdditionalSearchResults(extendedResult);
        docViewer.setActiveSearchResult(extendedResult[0]);
      }
    });
  }
}

const WebViewer = window.WebViewer;
WebViewer({
  initialDoc: 'assets/webviewer-demo-annotated.pdf',
  enableFilePicker: true,
  path: 'webviewer/lib',
  licenseKey: '<code class="expression">visitor.claims.wvKey || "YOUR_LICENSE_KEY"</code>',
}, document.getElementById('viewer')).then((instance) => {
  const { documentViewer } = instance.Core;
  documentViewer.addEventListener('documentLoaded', function() {
    instance.UI.overrideSearchExecution(executeSearchOnBackendFactory(documentViewer));
  });
});

function getPoints() {
  return {
    'x1': this.x1,
    'y1': this.y1,
    'x2': this.x2,
    'y2': this.y2,
    'x3': this.x3,
    'y3': this.y3,
    'x4': this.x4,
    'y4': this.y4,
  };
}

</code></pre>

{% endtab %}

{% tab title="api.js" %}

<pre class="language-js" data-line-numbers><code class="lang-js">const express = require('express');
const { PDFNet } = require('@pdftron/pdfnet-node');
const licenseKey = '<code class="expression">visitor.claims.wvKey || "YOUR_LICENSE_KEY"</code>';
const router = express.Router();
const MAX_RESULTS = 1000;

function buildSearchMode(options = {}) {
  const SearchMode = PDFNet.TextSearch.Mode;
  let searchMode = SearchMode.e_page_stop | SearchMode.e_highlight;

  if (options.caseSensitive) {
    searchMode |= SearchMode.e_case_sensitive;
  }
  if (options.wholeWord) {
    searchMode |= SearchMode.e_whole_word;
  }
  if (options.regex) {
    searchMode |= SearchMode.e_reg_expression;
  }
  if (options.ambientString) {

  }
  searchMode |= SearchMode.e_ambient_string;
  return searchMode;
}

function searchFromDocument(searchString, searchOptions, onSearchResultFound, onSearchDone) {
  return async function searchFromDocument() {
    if (!searchString) {
      // if no search string given, do not proceed any further
      return onSearchDone();
    }
    // Open document
    const document = await PDFNet.PDFDoc.createFromFilePath('./assets/webviewer-demo-annotated.pdf');
    let textSearchMode = buildSearchMode(searchOptions);
    // create new text search for document and set correct search mode
    const textSearch = await PDFNet.TextSearch.create();
    await textSearch.begin(document, searchString, textSearchMode);
    let iteration = 1;
    let done = false;
    while (!done &#x26;&#x26; iteration &#x3C; MAX_RESULTS) {
      // run() return results one by one. We'll run search as long as document has not reach to the end
      // or if the max result size is not limited
      // TODO: make sure this is not awaiting the response
      const result = await textSearch.run();
      if (result.code === PDFNet.TextSearch.ResultCode.e_found) {
        // highlight information is returned in result. We return all quads to the client
        // so we can show where in the document search keyword was found.
        const highlight = result.highlights;
        highlight.begin(document);
        let quadsInResults = [];
        while ((await highlight.hasNext())) {
          const quads = await highlight.getCurrentQuads();
          quadsInResults = quadsInResults.concat(quads);
          await highlight.next();
        }
        result.quads = quadsInResults;
        onSearchResultFound(result);
      }
      if (result.code === PDFNet.TextSearch.ResultCode.e_done) {
        onSearchDone();
        done = true;
      }
      iteration++;
    }
  }
}

function stringToBoolean(value) {
  return value === 'true';
}

router.get('/search', function(req, res) {
  // use search keyword from request query parameter
  let keyword = req.query.keyword;
  const searchOptions = {
    caseSensitive: stringToBoolean(req.query.caseSensitive),
    wholeWord: stringToBoolean(req.query.wholeWord),
    regex: stringToBoolean(req.query.regex),
  }
  if (!keyword) {
    return res.status(400).send('Bad request. Keyword query parameter missing');
  }

  res.setHeader('Content-Type', 'application/json');
  const results = [];
  function onSearchResultFound(result) {
    results.push(result);
  }

  function onSearchDone() { }

  PDFNet.runWithCleanup(searchFromDocument(keyword, searchOptions, onSearchResultFound, onSearchDone), licenseKey).then(
    function onFulfilled() {
      res.status(200).json(results);
    },
    function onRejected(error) {
      // log error and close response
      console.error('Error while searching', error);
      res.status(503).send();
    }
  );
});

module.exports = router;

</code></pre>

{% 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/webviewer-server-side-search.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.
