Easy Web PDF Viewer With jQuery And pdf.js - pdfjs-viewer

Easy Web PDF Viewer With jQuery And pdf.js - pdfjs-viewer

As web developers, we are always on the lookout for new ways to improve our user's experience. That's why I'm excited to share with you a new jQuery plugin called pdfjs-viewer.

This plugin is based on mozilla's pdf.js library, and provides a simple way for your users to view PDF documents directly in their web browser.

In this tutorial, I'll show you how to install and use the pdfjs-viewer jQuery plugin, as well as some of its features. So let's get started!

How to use it:

1. Load the necessary jQuery and pdf.js libraries in the document.

2. Load the OPTIONAL Material Icons.

3. Load the pdfjs-viewer plugin's files.

4. Initialize the pdf.js library.

// Let's initialize the PDFjs library var pdfjsLib = window['pdfjs-dist/build/pdf']; // The workerSrc property shall be specified. pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js';

5. Emebd a PDF viewer in an HTML element you specify.

var pdfViewer = new PDFjsViewer($('.pdfjs-viewer')); // load a PDF file pdfViewer.loadDocument('test.pdf');
let pdfViewer = document.getElementById("viewer");

5. Add a custom toolbar to the PDF viewer.

var pdfViewer; 

6. This example shows how to create a fullscreen PDF viewer with thumbnail support.

Adjust width Adjust height Fit page 50% 75% 100% 125% 150% 200% 300% 400%
Thumbnails.rotate(-90, true).then(() => pdfThumbnails.setZoom("fit"));'> pdfThumbnails.setZoom("fit"));'>

Cargue un fichero

const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const PDFFILE = urlParams.get('doc')??"test.pdf"; function dataURItoBinArray(data) < // taken from: https://stackoverflow.com/a/11954337/14699733 var binary = atob(data); var array = []; for(var i = 0; i < binary.length; i++) < array.push(binary.charCodeAt(i)); >return new Uint8Array(array); > /** Function to load a PDF file using the input=file API */ document.querySelector("#opendoc").addEventListener("change", function(e) < let file = e.target; let reader = new FileReader(); reader.onload = async function() < await pdfViewer.loadDocument(); await pdfThumbnails.loadDocument().then(() => pdfThumbnails.setZoom("fit")); > if (file.files.length > 0) < reader.readAsDataURL(file.files[0]); document.querySelector('#filedownload').download = document.querySelector('#opendoc').files[0].name; >>); /** Sets the document in horizontal scroll by changing the class for the pages container and refreshing the document * so that the pages may be displayed in horizontal scroll if they were not visible before */ function setHorizontal() < document.querySelector(".maindoc").classList.add("horizontal-scroll"); pdfViewer.refreshAll(); >/** Toggles the visibility of the thumbnails */ function togglethumbs(el) < if (el.classList.contains('pushed')) < el.classList.remove('pushed'); document.querySelector('.thumbnails').classList.add('hide'); >else < el.classList.add('pushed'); document.querySelector('.thumbnails').classList.remove('hide'); >> /** Toggles hiding the current page */ function hideselected() < let $selected = pdfThumbnails.$container.find('.selected'); let i = $selected.data('page'); $selected.toggleClass('hidden'); pdfViewer.$container.find('.pdfpage[data-page="' + i + '"]').toggleClass('hidden'); pdfViewer.scrollToPage(i); >/** Now create the PDFjsViewer object in the DIV */ let pdfViewer = new PDFjsViewer($('.maindoc'), < zoomValues: [ 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4 ], /** Update the zoom value in the toolbar */ onZoomChange: function(zoom) < zoom = parseInt(zoom * 10000) / 100; $('.zoomval').text(zoom + '%'); >, /** Update the active page */ onActivePageChanged: function(page) < let pageno = $(page).data('page'); let pagetotal = this.getPageCount(); if (! $(page).hasClass('hidden')) < pdfThumbnails.setActivePage(pageno); $('#pageno').val(pageno); $('#pageno').attr('max', pagetotal); $('#pagecount').text('de ' + pagetotal); >>, /** zoom to fit when the document is loaded and create the object if wanted to be downloaded */ onDocumentReady: function () < pdfViewer.setZoom('fit'); pdfViewer.pdf.getData().then(function(data) < document.querySelector('#filedownload').href = URL.createObjectURL(new Blob([data], )); document.querySelector('#filedownload').target = '_blank'; >); > >); /** Load the initial PDF file */ pdfViewer.loadDocument(PDFFILE).then(function() < document.querySelector('#filedownload').download = PDFFILE; >); /** Create the thumbnails */ let pdfThumbnails = new PDFjsViewer($('.thumbnails'), < zoomFillArea: 0.7, onNewPage: function(page, i) < $('>) >, onDocumentReady: function() < this.setZoom('fit'); >>); pdfThumbnails.setActivePage = function(pageno) < this.$container.find('.pdfpage').removeClass('selected'); let $npage = this.$container.find('.pdfpage[data-page="' + pageno + '"]').addClass('selected'); $('#hideselected').removeClass('pushed'); if ($npage.hasClass('hidden')) $('#hideselected').addClass('pushed'); if (!this.isPageVisible(pageno)) < this.scrollToPage(pageno); >>.bind(pdfThumbnails); pdfThumbnails.loadDocument(PDFFILE);

7. All default options and callbacks.

let pdfViewer = new PDFjsViewer($('.pdfpages'), < // Fraction of the area of the page that has to be visible to be considered that it is visible visibleThreshold: 0.5, // Number of pages to load appart from the currently visible one (to enable fast scrolling) extraPagesToLoad: 3, // The class used for each page (the div that wraps the content of the page) pageClass: "pdfpage", // The class used for the content of each page (the div that contains the page) contentClass: "content-wrapper", // Posible zoom values to iterate over using "in" and "out" zoomValues: [ 0.25, 0.5, 0.75, 1, 1.25, 1.50, 2, 4, 8 ], // Percentage of the container that will be filled with the page zoomFillArea: 0.95, // Enhance the resolution for the pages renderingScale: 1.5, // Function called when a document has been loaded and its structure has been created onDocumentReady: () =><>, // Function called when a new page is created (it is binded to the object, and receives a jQuery object as parameter) onNewPage: (page, i) => <>, // Function called when a page is rendered onPageRender: (page, i) => <>, // Function called when the zoom level changes (it receives the zoom level) onZoomChange: (zoomlevel) => <>, // Function called whenever the active page is changed (the active page is the one that is shown in the viewer) onActivePageChanged: (page, i) => <>, // Function called to get the content of an empty page emptyContent: () => $(' < $(`, >);
// load a PDF file and returns a promise // the document can be either an url or a bin array. pdfViewer.loadDocument(document); // force re-init pdfViewer.forceViewerInitialization(); // refresh all pages pdfViewer.refreshAll(); // get the active page pdfViewer.getActivePage(); // go to the first page pdfViewer.first(); // go to the last page pdfViewer.last(); // go to the next page pdfViewer.next(); // back to the previous page pdfViewer.prev(); // get the number of pages pdfViewer.getPageCount(); // retrieve all the pages of the document pdfViewer.getPages(); // go to a specific page pdfViewer.scrollToPage(i); // check if the page is visible isPageVisible(i); // set zoom level // it is possible to use a float value which represents a fraction or a keyword 'in', 'out', 'width', 'height' or 'fit' pdfViewer.setZoom(zoom); // get the current zoom level pdfViewer.getZoom(); // rotate the pages pdfViewer.rotate(deg, accumulate = false);

Changelog:

  • includes the renderingScale option to enhance the resolution for the pages
  • bugfixes

This awesome jQuery plugin is developed by dealfonso. For more Advanced Usages, please check the demo page or visit the official website.

  • Prev: Modern-looking Custom Audio Player With jQuery - oyoplayer
  • Next: Filter A Group Of Elements With Fade/Slide Animations - jqSearch