Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search with pdf.js?

I'm displaying a pdf file with pdf.js in my Ionic App. I do not use viewer.js and viewer.html, because I need a totally different layout. Now I have a custom search bar and I want to highlight terms in my pdf file. Is there a function I can invoke to do this?

I'm rendering the file like this:

$scope.renderPages = function(pdfDoc) {
    $scope.pdfFile = pdfDoc;
    for(var num = 1; num <= pdfDoc.numPages; num++){
        pdfDoc.getPage(num).then($scope.renderPage);
    }
}

$scope.renderPage = function(page) {
    var viewport = page.getViewport(1);
    scale = document.getElementById('viewer').clientWidth / viewport.width;
    viewport = page.getViewport(scale);

    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var renderContext = {
        canvasContext: ctx,
        viewport: viewport
    };

    canvas.height = viewport.height;
    canvas.width = viewport.width;

    var canvasContainer = document.getElementById('viewer');
    canvasContainer.appendChild(canvas);

    page.render(renderContext);
}

HTML:

<div id="viewerContainer" style="padding-bottom: 100%; padding-top: 20px;">
    <div id="viewer" class="viewer-styles">
    </div>
</div>
like image 712
chocolate cake Avatar asked Feb 19 '16 09:02

chocolate cake


People also ask

Does PDF JS work in Chrome?

What Browsers does PDF. js Support. PDF. js is used within Mozilla Firefox today as the built-in PDF viewer, and it works well within a website when viewed using the latest versions of Chrome and Firefox, whether through the pre-built PDF.

Is PDF JS free to use?

PDF. js is a good free option if you're willing to invest time into implementing a UI for it. The project comes with some examples and API docs.

Is PDF JS open source?

PDF. js is an open source project and always looking for more contributors.


1 Answers

Now I found the solution!

var container = document.getElementById('viewerContainer');
var viewer = document.getElementById('viewer');


var pdfViewer = new PDFViewer({ 
   container: container,
   viewer: viewer
});

$scope.pdfFindController = new PDFFindController({
   pdfViewer: pdfViewer
);

pdfViewer.setFindController($scope.pdfFindController);

container.addEventListener('pagesinit', function () {
    pdfViewer.currentScaleValue = 'page-width';                            
});

PDFJS.getDocument(MY_PATH_TO_THE_PDF).then(function (pdfDocument) {
    pdfViewer.setDocument(pdfDocument);
});

Search for terms:

$scope.pdfFindController.executeCommand('find', {
    caseSensitive: false, 
    findPrevious: undefined,
    highlightAll: true, 
    phraseSearch: true, 
    query: "myQuery"
});

And I had to import the viewer.js.

The code that I posted in the question is not needed anymore. The PDFViewer renders the pdf.

like image 51
chocolate cake Avatar answered Oct 12 '22 14:10

chocolate cake