How to Build a PDF Viewer with JavaScript?

Tutorials | PDF.js · JavaScript PDF Viewer · ComPDFKit for Web Thu. 07 Dec. 2023

As web applications continue to evolve, the ability to handle PDF documents within these platforms has become increasingly crucial. Whether you're looking to render, annotate, or manipulate PDF files, selecting the right PDF software development kit (SDK) can make a significant difference in your project's success. 

 

The open-source PDF viewer library PDF.js is a Portable Document Format (PDF) viewer that is built with HTML5 and has been widely used in some other PDF libraries like react-pdf, ngx-extended-pdf-viewer, pdfvuer, etc. 

 

In this guide, we will introduce how to build a JavaScript PDF Viewer with PDF.js and the commercial PDF SDK — ComPDFKit for Web. At the bottom of the article, you will see when you will need a commercial PDF library.

 

Steps to Build a JavaScript PDF Viewer with PDF.js

 

1. Create an “index.html” file with the following code. Then, the PDF will display.

<!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/pdfjs-dist@4.0.269/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/pdfjs-dist@4.0.269/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>



How to Build a JavaScript PDF Viewer with ComPDFKit for Web

 

1. Import the “@compdfkit” folder into the root of your project.

 

2. Initialize the ComPDFKit for Web in your project by calling ComPDFKitViewer.init().

 

3. Invoke the init function by supplying the URL of the PDF you wish to render, along with your valid license key.

import ComPDFKitViewer from "/@compdfkit/webviewer";

export default function Home() {
  let init = false
  const viewer = useRef(null);
  let docViewer = null
  useEffect(() => {
    if (init) return
    init = true

    ComPDFKitViewer.init({
      pdfUrl: 'Your PDF Url',
      license: 'Input your license here'
    }, viewer.current).then((core) => {
      docViewer = core.docViewer
    })
  });

  return (
    <div id="webviewer" ref={viewer}></div>
  )
}

 

4. PDF will be opened and displayed.

 

PDF Viewer with ComPDFKit for Web



Add More PDF Capabilities

 

You have learned the steps to create a robust PDF Viewer using JavaScript with the aid of PDF.js and ComPDFKit for Web. For straightforward PDF viewing needs, the open-source library PDF.js is a suitable choice. However, for more advanced functionalities such as editing, annotating, signing, comparing, applying OCR, and redaction, ComPDFKit for Web is a nice choice.

 

ComPDFKit for Web offers:

 

         - Server-supported and self-contained web PDF SDK options.

         - A high-fidelity rendering engine for superior document quality.

         - A versatile viewing experience with multiple themes, scroll options, display modes, search functionality, and zoom capabilities.

         - Mature PDF annotation tools.

         - Electronic and digital signatures meeting all your sign needs.

         - The completion of various forms.

         - Independent and robust PDF technology.

         - Customizable UI options to seamlessly integrate into your application.

         - Prompt and responsive technical support.


Click and experience these features directly through the free online demo now. Should you have any inquiries or wish to request a free trial of the SDK, please reach out to the ComPDFKit team.

Ready to Get Started?

Download our all-in-one ComPDFKit for free and run it to your project within minutes!