PDF.js v4-Open findBar by default

34 Views Asked by At

I embedded a PDF using pdfjs-4.0.379, and in the previous version (version 2) I had something similar to this:

...
key: "setHash",
    value: function setHash(hash) {
        //aqui
      var pageNumber, dest;      

      if (hash.includes("=")) {
        var params = (0, _ui_utils.parseQueryString)(hash);
        
        if ("search" in params) {
          this.eventBus.dispatch("findfromurlhash", {
            source: this,
            query: params.search.replace(/"/g, ""),
            phraseSearch: params.phrase === "true"
          });
        }
        
         if ('search' in params) { 
              PDFViewerApplication.findBar.open(); 
              PDFViewerApplication.findBar.findField.value = params.search; 
              PDFViewerApplication.findBar.highlightAll.checked = true; 
              PDFViewerApplication.findBar.findNextButton.click(); 
        }
...

But how can i implement that in the current version?

I found a similar answer in this link, but it didn't really answer my question.

1

There are 1 best solutions below

0
redrobot753 On

Let me show you one possible way. I use a pdfjs-viewer-element just to simplify PDF.js setup:

  1. Install the pdfjs-viewer-element:
<script type="module" src="https://cdn.skypack.dev/pdfjs-viewer-element"></script>
  1. Specify the PDF.js release directory with viewer-path and path to PDF file with src attributes.
<pdfjs-viewer-element
  id="viewer"
  src="/public/sample-pdf-with-images.pdf"
  viewer-path="/public/pdfjs-4.0.379-dist"
  style="height: 100dvh">
</pdfjs-viewer-element>
  1. Wait for viewer initialization, then wait for pages loaded. Finally open find bar and search:
document.addEventListener('DOMContentLoaded', async () => {
  const viewer = document.querySelector('#viewer')
  // Wait for the viewer initialization
  const viewerApp = await viewer.initialize()
  // Wait for pages loaded, open find bar and search
  viewerApp.eventBus.on('pagesloaded', () => {
    viewerApp.findBar.open()
    viewerApp.findBar.findField.value = 'na' 
    viewerApp.findBar.highlightAll.checked = true
    viewerApp.findBar.findNextButton.click()
  })
})

Check out full sample https://github.com/alekswebnet/pdfjs-viewer-element/blob/master/demo/opened-findbar.html