Discover the power of pdf.js for effective online browsing!

Currently, I am using pdf.js to display a PDF file in my Ionic App. Instead of utilizing viewer.js and viewer.html, I have created a custom layout with a unique search bar. One feature I am looking to implement is the ability to highlight terms within the PDF file. Is there a specific function that can be called to achieve this?

The method I am using to render the file is as follows:

$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);
}

In the HTML section:

<div id="viewerContainer" style="padding-bottom: 100%; padding-top: 20px;">
    <div id="viewer" class="viewer-styles">
    </div>
</div>

Answer №1

Finally, the solution has been discovered!

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);
});

Let's search for some terms:

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

Additionally, I needed to import the viewer.js file.

The initial code provided in the question is now obsolete as the PDFViewer effectively renders the PDF.

Answer №2

Although this thread is old, it's still important for people to understand how the package functions now. I've found a way to make it work effectively by using an iframe to display the PDF content.

const iframeDocument = document.getElementById('pdf-js-viewer').contentWindow;
let searchText = "TheTextYouWantoToHighlight";

iframeDocument.PDFViewerApplication.pdfViewer.findController.executeCommand('find', {
    caseSensitive: false,
    findPrevious: undefined,
    highlightAll: true,
    phraseSearch: true,
    query: searchText
})

With the latest version of pdfjs, there may be errors in the console prompting to use dispatch event. The following code resolves that error and functions as intended.

const iframeDocument = document.getElementById('pdf-js-viewer').contentWindow;
let searchText = "TheTextYouWantoToHighlight";
iframeDocument.PDFViewerApplication.eventBus.dispatch('find', {
    caseSensitive: false,
    findPrevious: undefined,
    highlightAll: true,
    phraseSearch: true,
    query: searchText
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting numerical values from the computed transform matrix in Javascript? The result might be NaN

Recently, I've been working with the transform computed style property. matrix3d(1.5, -7, 2, 0, 7, 1.5, 0, 0, -3, 1, 1, 0, 100, 0, 0, 1) Now, my goal is to convert this into an array of numbers: var s = window.getComputedStyle(element); var mattrix ...

extract values from a JavaScript function on a website

Currently, I am facing a challenge in automatically retrieving elements from a webpage and I seem to be stuck on a few things. My approach involves looping through all classes named 'trList' using document.getElementsByClassName('trList&apo ...

Issues with AngularJS functionality – $route.reload() not functioning as expected

I'm attempting to refresh the page using $route.reload(): var App = angular.module("App", ["ngRoute"]); var idx = 0; App.controller("List", function ($scope, $route) { $scope.changeWallet = function (index) { idx = index; $r ...

What is the best way to send a promise back from my service to my controller?

While I have posed this question in various forms, I now find myself stuck with a piece of code that contains an elusive bug. My Angular service looks like this: .service("lookupDataService", [ '$q', '$http', '$timeout&ap ...

ng-click stops functioning after ng-bind-html is compiled

I am struggling with integrating a directive into my AngularJS project. app.directive("dir", function($compile, $sce){ return{ restrict: "E", link: function(scope, element, attr){ scope.$watch('content',function() ...

Angular 8 can sometimes cause CSS to become disorganized upon page load

In the process of developing my angular project, I've integrated pre-designed HTML templates. Implementing lazy loading for page loading has led to an issue where the CSS appears distorted, as shown in the attached gif image. https://i.sstatic.net/7UZ ...

Integrating a module function with an AngularJS service

After reviewing the contents of these two links 1 and enter link description here, I've gained insight into the importance of maintaining clean and modular code. The approach outlined in the aforementioned links advocates for separating functions int ...

Retrieve the body's coordinates when dragging an element using the jQuery UI library

How can I obtain the coordinates of a dragged div upon drag and drop action, including left, right, and top positions? Additionally, how do I then use Ajax to post these coordinates? An example link can be found at jsfiddle.net/qPw92 <html> &l ...

A JavaScript function that yields no value is undefined

In my AngularJS project, I have a function that makes a GET request to the backend multiple times and returns data. Here is an example of how the function is used: function getFunction(inputData) { $http.get('request URL', { params: 'so ...

Are elements loaded and hidden by ng-hide and ng-show, or does loading only occur with ng-show?

Is this method of programming effective for handling large elements such as 10 mb images? Are there alternative solutions that would work better? ...

Swap out an element in a list that does not correspond to any element in a separate list with a designated value

I am fairly new to Javascript and currently struggling with looping through an array and replacing items. I hope my explanation is clear. Here is the initial array: [ '1:1', 'blah', '1:2', undefined, '1:3' ...

Error: The absence of an element identified by the locator does not cause the protractor spec to fail, but rather it executes successfully

This automation framework follows the page object model and utilizes the async/await approach rather than promises. TypeScript is used, with compilation to JavaScript (protractor) for script execution. Page Object: async addProjectDetails(): Promise< ...

Finding and clicking on a specific ng-click attribute within a class in AngularJS applications can be achieved using Selenium Protractor

I found this code in the view source <div class="row-fluid"> <div class="span4"> <div class="well tile table-clickable" ng-click="move('mjass')"> <h3> Music Jass </h3> <div class="row-fluid cellBody"> <div ...

Setting the focus on an input when updating a property in the Pinia store using Vue

When a component I have is clicked, it triggers a function in the store: <button @click="this.store.foo()"></button> Within the store, I am updating a specific property: state: () => ({ focusIn: false, }), actions: { foo() { ...

Sorting Tables (Implementing ng-repeat and eliminating duplicate column names with ng-if)

I have a table with data displayed using ng-repeat and it is currently sorted properly. To view the initial setup, check out the first fiddle. http://jsfiddle.net/HB7LU/10201/ <tr ng-repeat="each in list | orderBy:predicate:reverse"> I am aiming t ...

Injecting Dependencies Into ExpressJS Routes Middleware

Hey there! I'm currently working on injecting some dependencies into an expressjs route middleware. Usually, in your main application, you would typically do something like this: const express = require('express'); const userRouter = requi ...

jQuery selector unable to locate the specified class in the table row

After receiving an array of strings as a response from an SQL query, I am using JavaScript to dynamically add this data as rows to an HTML table: loadUsers: function() { . . . function displayUsersOnTable(response) { for(var i = ...

Inkwell shifts bespoke quality

I am currently utilizing Quill (v.2.0.0) with quill-better-table (v.1.2.10) within my Angular 13 project. I am attempting to incorporate a custom attribute to the table tag, as shown below: <table class="quill-better-table" custom-attribute=& ...

The error occurred while attempting to save the file to disk: 'setHeader() requires both a name and a value to be set.'

I am working on enabling image file uploads to the Node.js server in a MEAN Stack application. Utilizing ng-file-upload for the client-side angular directive has been successful so far. However, I have encountered an issue when attempting to pass the image ...

error when trying to bind attributes to knockout components

I am trying to dynamically add an id attribute to a tag, but it keeps giving me an error. "Uncaught ReferenceError: Unable to process binding "attr: function (){return {id:id} }" Message: id is not defined" Here is my HTML code- <label data-bind= ...