Tutorials

How to Build JavaScript PDF Viewer with PDF.js

By ComPDFKit | Wed. 27 Nov. 2024
WebJavaScript

When building a JavaScript PDF viewer, you have two main options: commercial libraries like ComPDFKit for Web, which offer comprehensive features, professional support, and regular updates, though they come at a cost. Alternatively, if your goal is simply to create a basic PDF viewer without advanced features, free open-source libraries like PDF.js can effectively meet your needs.

 

This guide is designed to walk you through using both PDF.js and ComPDFKit for Web to build a JavaScript PDF viewer, allowing users to view and interact with PDF documents directly in a web browser without the need for an external PDF reader.

 

build-javascript-pdf-viewer

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

 

How to Build JavaScript PDF Viewer with Open Source PDF.js

 

PDF.js is a powerful JavaScript library developed by Mozilla that allows the rendering of Portable Document Format (PDF) files directly in web browsers. It provides a seamless, plugin-free PDF viewing experience. As an open-source project with community-driven development, PDF.js is an ideal choice for web developers looking to add PDF functionality to their applications.

 

Requirements

  • Node.js

  • A package manager like npm or yarn. When you install Node.js, npm is installed by default.

 

Step 1: Get PDF.js

 

 <script src="https://unpkg.com/[email protected]/build/pdf.min.mjs" type="module"></script>

 

Step 2: Loading a PDF File and scale the PDF file.

 

  <script type="module">

    // If absolute URL from the remote server is provided, configure the CORS header on that server.

    var url = 'https://pdftron.s3.amazonaws.com/downloads/pl/demo-annotated.pdf';

    var { pdfjsLib } = globalThis;

    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://unpkg.com/[email protected]/build/pdf.worker.mjs';

    var loadingTask = pdfjsLib.getDocument(url);

    loadingTask.promise.then(function(pdf) {

      console.log('PDF loaded');

      var documentContainer = document.getElementsByClassName('webviewer')[0];

      const numPages = pdf.numPages

      for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {

        pdf.getPage(pageNumber).then(function(page) {

          console.log('Page loaded');

          var scale = 1;

          var viewport = page.getViewport({scale: scale});

      }

    }, function (reason) {

      // PDF loading error

      console.error(reason);

    });  </script>

 

Step 3: The following shows all the code to build PDF viewer with PDF.js (A PDF file example is provided by URL.): 

 

<!DOCTYPE html>

<html lang="en">

  <head>

  <meta charset="UTF-8" />

  <meta http-equiv="X-UA-Compatible" content="IE=edge" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>PDF Viewer in JavaScript</title>

  <style>

    .webviewer {

      width: 100vw;

      display: flex;

      flex-direction: column;

      align-items: center;

      background-color: #ccc;

    }

    .webviewer canvas {

      margin-top: 20px;

    }

  </style>

  </head>

  <body>

    <div class="webviewer"></div>

  </body>

  <script src="https://unpkg.com/[email protected]/build/pdf.min.mjs" type="module"></script>

  <script type="module">

    // If absolute URL from the remote server is provided, configure the CORS header on that server.

    var url = 'https://pdftron.s3.amazonaws.com/downloads/pl/demo-annotated.pdf';

    var { pdfjsLib } = globalThis;

    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://unpkg.com/[email protected]/build/pdf.worker.mjs';


    var loadingTask = pdfjsLib.getDocument(url);

    loadingTask.promise.then(function(pdf) {

      console.log('PDF loaded');


      var documentContainer = document.getElementsByClassName('webviewer')[0];

      const numPages = pdf.numPages

      for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {

        pdf.getPage(pageNumber).then(function(page) {

          console.log('Page loaded');


          var scale = 1;

          var viewport = page.getViewport({scale: scale});


          // Prepare canvas using PDF page dimensions

          const canvas = document.createElement('canvas')

          var context = canvas.getContext('2d');

          canvas.height = viewport.height;

          canvas.width = viewport.width;

          // Render PDF page into canvas context

          var renderContext = {

            canvasContext: context,

            viewport: viewport

          };

          var renderTask = page.render(renderContext);

          renderTask.promise.then(function () {

            console.log('Page rendered');

            documentContainer.append(canvas)

          });

        });

      }

    }, function (reason) {

      // PDF loading error

      console.error(reason);

    });

  </script>

</html>

 

The benefits and limitations of using PDF.js

 

Benefits:

 

  • Ready-to-use reader UI

  • Built-in zoom functionality

  • Multiple viewing and search options

 

Limitations:

 

  • Text selection and search can be unreliable

  • Struggles with PDFs that are graphics-heavy or complex

  • Limited browser support outside of Chrome, Firefox, and Edge

  • Primarily a PDF reader, without advanced features

 

 

Create JavaScript PDF Reader With ComPDFKit

 

ComPDFKit is dedicated to providing developers with professional PDF solutions. Our commercial JavaScript document viewer library integrates seamlessly into your web applications. Additionally, ComPDFKit’s comprehensive and easy-to-use documentation enables developers to add advanced PDF functionality with just a few lines of code, allowing users to view, annotate, edit, and sign documents directly in the browser. Out of the box, it offers a fully customizable UI that can be extended or simplified to suit your unique use case.

 

Video Guide: Create a JavaScript PDF Viewer by ComPDFKit

 

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

 

Requirements:

 

  • The latest stable version of Node.js.

  • A package manager compatible with npm.

  • Get the License Key: Go to ComPDFKit's pricing page to get a free 30-day license to integrate the ComPDFKit PDF viewer library for Web.

  • JavaScript PDF Library package of ComPDFKit PDF viewer.

 

Step 1:Install the ComPDFKit for Web package from npm into your Vanilla JS project

 

npm i @compdfkit_pdf_sdk/webviewer --save

 

Step 2: Add the "webviewer" folder which contains the required static resource files to run the ComPDFKit Web demo, to your project’s public resource folder. The folder you need to copy is node_modules/@compdfkit_pdf_sdk/webviewer/dist.

 

cp ./node_modules/@compdfkit_pdf_sdk/webviewer/webviewer.global.js ./

cp -r ./node_modules/@compdfkit_pdf_sdk/webviewer/dist ./webviewer

 

Step 3: Create index.html

 

What you need to know is that when you use the JavaScript PDF viewer SDK, you need to use the parameter path to tell it where the static resources are located. If you don't do this step, then they are relative to the current path"

 

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>ComPDFKit Web Viewer</title>

</head>

<!-- Import WebViewer as a script tag -->

<script src='./webviewer.global.js'></script>

<body>

  <div id="app" style="width: 100%; height: 100vh;"></div>

</body>

</html>

 

Step 4: Add a script tag and initialize ComPDFKit Viewer for Web using Vanilla JavaScript.

 

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>ComPDFKit Web Viewer</title>

</head>

<!-- Import WebViewer as a script tag -->

<script src='./webviewer.global.js'></script>

<body>

  <div id="app" style="width: 100%; height: 100vh;"></div>

​

  <script>

    let docViewer = null;

​

    ComPDFKitViewer.init({

      path: '/',

      pdfUrl: '/webviewer/example/developer_guide_web.pdf',

      license: '<Input your license here>'

    }, document.getElementById('app')).then((core) => {

      docViewer = core.docViewer;

​

      docViewer.addEvent('documentloaded', async () => {

        console.log('document loaded');

      })

    })

  </script>

</body>

</html>

 

Step 5: In order to display on the local host, we need to set up the server environment in this step.

 

npm install -g http-server

 

Step 6: Serve Your Website

 

http-server -a localhost -p 8080

 

Open http://localhost:8080 on your browser. Then you can see the PDF file you want to display like this:

 

 

Why Choose ComPDFKit for Web?

 

  • Professional Support and Services

  • Comprehensive Functionality and Superior Performance

  • Customizable Libraries and Deliverables Based on Requirements

  • Default Functional UI Provided

  • Regular Updates and Security Patches

  • Advanced Feature Integration

  • Flexible pricing  & Community license

 

 

Final Words

 

Developing a JavaScript-based PDF reader is both challenging and highly rewarding. From choosing the right PDF library to implementing practical features, each step requires developers to carefully weigh their options. However, as the complexity of the project increases, many teams eventually migrate to commercial PDF libraries, such as ComPDFKit. The advantages of commercial libraries in terms of features and support often make them a more attractive choice.

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free