Skip to content

View and Hit-Highlight a PDF Document in Browser.

Universal Search Server Endpoints come with an embeddable PDF Viewer to embed a PDF Viewer with multi-color hit highlighting into your website.

Embed PDF Viewer and Load Document

The PDF Viewer is located in /pdfViewer/web/viewer.html.

To load a PDF, the URL to the PDF file must be passed as file query parameter URI encoded. You should pass /api/pdf?docid=${DocID}&index=${Index} as the file url.

Example

Html

<iframe id="pdfViewer"></iframe>

Javascript

let pdfViewer = document.getElementById('pdfViewer');
let docID = 1;
let index = 'Example Index';
let pdfFileUrl = `/api/pdf?docid=${docID}&index=${index}`;
// Trigger the iframe to load the PDF Viewer and open the specified document.
pdfViewer.setAttribute('src',
'pdfViewer/web/viewer.html?file=' + encodeURIComponent(pdfFileUrl));

Highlight Hits in PDF Viewer

Highlight Coordinates must be requested from the API, then forwarded to the PDF Viewer via PostMessage. Refer to the code below.

// Listen for the iframe telling us that the document finished loading.
addEventListener('message',(event) => {
    if (event.data && event.data === "PDF_LOADED") {
        // The PDF has loaded in the iframe. Now retrieve the hits
        let requestData = {
            DocID: docID,
            Index: index,
            Request: "Apples" // The search term to highlight.
        }
        fetch('/api/pdf', {
            method: 'POST',
            mode: 'same-origin',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        }).then((response) => {
            return response.json();
        }).then((responseJson) => {
            // Append the 'RENDER_HITS' action to the json
            responseJson.action = 'RENDER_HITS';
            // Forward the json to the PDF Viewer.
            pdfViewer.contentWindow.postMessage(responseJson, "*");
            // The PDF Viewer will now display highlighted hits.
        });               
    }
}, false);

Last update: June 21, 2020