Tigerware
Tigerware

Reputation: 3904

Search pdf page using PdfJs & PDFFindController constructor

I am displaying pdf documents using PDF.js. Now I want to be able to search for text within a pdf document. There are some examples on how to do this, but they do not work, because the constructor for PDFFindController cannot be found.

Displaying the document worked fine using

let loadingTask = pdfjsLib.getDocument(url);
loadingTask.promise.then((pdf: any) => { /* display code here */ }

But when I try to create a PDFFindController as suggested in this Example it fails.

new pdfjsLib.PDFFindController();

The error in Firefox shows as:

TypeError: pdfjs_dist_1.default.PDFFindController is not a constructor

I am not sure how to proceed from here, since it looks similar to the example and others I found on stackoverflow.

When I print the library object to the console it is not showing PDFFindController or even PDFViewer on this object, so I could imagine that PDFFindController requires a different library file, but the docs aren't to clear which file or how to import it using systemjs.

Upvotes: 1

Views: 3733

Answers (4)

GhosterNet
GhosterNet

Reputation: 43

executeCommand is obsolete now. you can use eventBus instead, like:

   var eventBus = PDFViewerApplication.pdfViewer.eventBus;
   var options = {
       type: "",
       query: phrase,
       caseSensitive: false,
       entireWord: false,
       highlightAll: true,
       phraseSearch: true,
   };

   eventBus.dispatch("find", options)

You also use the url with search parameter, like

var url = "/web/viewer.html?file=/mySample.pdf#page=1&search=my search phrase";

I hope it helps

Upvotes: 0

SONALI AGARWAL
SONALI AGARWAL

Reputation: 23

I was also getting this, and it took me forever to solve this. Here you go. You are getting that error because PDFLinkService() is not a function of PDFjsLib, you need to call that from PdfJsViewer.

Try this:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/web/pdf_viewer.js"></script>

const PdfJsViewer = window['pdfjs-dist/web/pdf_viewer'];
 const pdfLinkService = new pdfjsViewer.PDFLinkService({
  eventBus,
});

Rest you can check here: https://github.com/mozilla/pdf.js/blob/master/examples/components/simpleviewer.js

Upvotes: 1

amir
amir

Reputation: 11

You can use pdf.js search method. you should call it like this:

PDFViewerApplication.findController.executeCommand("find" + evt.type, {
query: evt.query,
phraseSearch: evt.phraseSearch,
caseSensitive: evt.caseSensitive,
entireWord: evt.entireWord,
highlightAll: evt.highlightAll,
findPrevious: evt.findPrevious });

just replace your search key with "evt.query".

Upvotes: 0

JacopoStanchi
JacopoStanchi

Reputation: 2146

Have you tried replacing pdfjsLib.PDFFindController() by pdfjsViewer.PDFFindController()?

Upvotes: 1

Related Questions