Tutorials

How to Build Javascript PDF Reader with Open Source PDF.js

By ComPDFKit | Thu. 07 Dec. 2023
WebJavaScript

 

How to Build Javascript PDF Reader with Open Source PDF.js

 

Commercial library ComPDFKit for Web, offers comprehensive features, professional support, and regular updates, but they come at a cost. Open-source library PDF.js provides free alternatives but may lack some advanced features and support. Understanding the specific needs of your project and the strengths and weaknesses of each library is crucial to making an informed decision.

 

In this article, we will demonstrate the differences between and developer guides for the open-source JavaScript PDF Viewer libraries - PDF.js and a commercial PDF viewer library - ComPDFKit. 

 

 

 

How to Choose the Right JavaScript PDF Viewer Library

 

Choose the proper PDF viewer libraries and follow the guides on integrating the JavaScript PDF viewer libraries to create open-source PDF readers. 

 

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

 

In this section, we'll dive into a detailed comparison of ComPDFKit and PDF.js.

 

JavaScript PDF Viewer Library

Commercial JavaScript PDF Viewer Library

Open-Source JavaScript PDF Viewer Library Comparison

ComPDFKit for Web

PDF.js

Features

Provide comprehensive features to process PDF files:


- Viewer

- Annotations

- Forms

- Document Editor

- Security

- Redaction

- Watermark

- Conversion

- Content Editor

- Document Comparison

- Signatures

- Measurement

- Optimization

- UI Customization

- Render PDF documents

- Search for PDF text

- View page thumbnails

- Zoom

- Rotate PDF pages

- Text and highlight annotations

- Fill out forms

- Bookmarks

- Outlines

Framework

Vue

React

Angular

Next.js

Nuxt.js

Svelte

SvelteKit

Vanilla JavaScript

PDF.js is a pure JavaScript library for rendering PDF files, and it can be used in any environment that supports JavaScript.

Advantages

- 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

- High performance

- Highly customizable

- Extensive documentation

- Active community

- Browser compatibility

Disadvantages

It's a commercial PDF viewer library, but provides discounts for individual developers and startups.

Larger size compared to others More complex to customize Requires more dependencies

 

 

Build PDF Viewer with PDF.js Open Source Javascript Library

 

Step 1: Requirements

 

To get started, you’ll need:

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

 

Step 2: Get PDF.js

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

 

Step 3: 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 4: 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>



Build PDF Viewer with ComPDFKit Vanilla PDF Viewer

 

To get started, you'll need the following prerequisites:

 

  • 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.

 

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

npm i @compdfkit_pdf_sdk/webviewer --save

 

Step1: 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

 

Step2: 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>

 

Step3: 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>

 

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

npm install -g http-server

 

Step5: 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:

 

ComPDFKit JavaScript PDF Viewer

 

Conclusion

 

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