PDF.js tutorial: Build a JavaScript PDF viewer (2026)
Table of contents
See how Nutrient Web SDK compares on rendering fidelity, annotations, forms, and support.
Build a canvas viewer with PDF.js for page navigation and zoom, or embed its full viewer for a broader interface. Then evaluate Nutrient Web SDK against your document task: reading, adding feedback, and returning a reviewed file. The loading examples don’t implement shared storage or approval workflows.
A JavaScript PDF viewer might help a customer read a statement, check a contract, or review a drawing inside your application. Start with what the reader must accomplish and what must remain in the saved document. This tutorial shows separate PDF.js and Nutrient implementations to help evaluate those needs.
Introduction to PDF.js
PDF.js is a JavaScript library from Mozilla that renders PDFs directly in the browser. It uses HTML5 and the Canvas API to display documents without plugins. Because it’s open source and actively maintained, many developers use it to add PDF viewing to their web apps. Later in this tutorial, you’ll load Nutrient Web SDK as another viewer option. A successful render is the starting point; verify the complete document task before deploying either implementation.
With PDF.js, you can:
- Render PDF files accurately across different browsers.
- Integrate PDF viewing capabilities without external plugins or software.
- Build both simple and advanced PDF viewers tailored to your application’s needs.
Requirements
Before getting started, make sure you have the following installed:
- Node.js(opens in a new tab)
- A package manager like npm(opens in a new tab) (included with Node.js) or yarn(opens in a new tab).
Understanding PDF.js architecture
PDF.js operates through three main layers:
- Core — Interprets the binary format of PDFs and performs heavy parsing operations, often running in a web worker(opens in a new tab) to keep the main thread responsive.
- Display — Builds on the core layer and provides an API for rendering PDF pages into
<canvas>elements using JavaScript. - Viewer — A ready-to-use interface with features like search, rotation, and a thumbnail sidebar.
To use PDF.js, download a recent copy(opens in a new tab) and integrate it into your project.
Building a basic PDF viewer
PDF.js enables rendering of PDFs via asynchronous JavaScript and XML (AJAX) and displaying them in a <canvas> element. Continue reading for a step-by-step guide to setting up a basic viewer.
Step 1 — Download PDF.js files
To render a specific page of a PDF into a <canvas> element, you can use the display layer.
To get started:
- Extract all the files in the downloaded copy of PDF.js.
- Move
pdf.mjsandpdf.worker.mjsfrom thebuild/folder of the download to a new empty folder. - Create an
index.htmlfile and anindex.jsfile.
The HTML file needs to point to the pdf.mjs source code and to the custom application code (index.js).
Creating the HTML file
Create the
canvaselement, which you want to render the PDF inside of:<!-- Canvas to place the PDF --><canvas id="canvas" class="canvas__container"></canvas>Create a toolbar inside the
<header>element to add navigation and zoom controls to the website. Add some icons for the previous (<), next (>), and zoom buttons. For that, you’ll use the Font Awesome(opens in a new tab) library; all you need to do is include the content delivery network (CDN) link for it. Then, add the following code to theindex.htmlfile:<!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><linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css"integrity="sha512-Kc323vGBEqzTmouAECnVceyQqyqdsSiqLQISBL29aUW4U/M7pSPA/gEUZQqv1cwx4OnYxTxve5UMg5GT6L4JJg=="crossorigin="anonymous"referrerpolicy="no-referrer"/><link rel="stylesheet" href="style.css" /></head><body><header><ul class="navigation"><li class="navigation__item"><!-- Navigate to the Previous and Next pages --><a href="#" class="previous round" id="prev_page"><i class="fas fa-arrow-left"></i></a><!-- Navigate to a specific page --><input type="number" value="1" id="current_page" /><a href="#" class="next round" id="next_page"><i class="fas fa-arrow-right"></i></a><!-- Page Info -->Page<span id="page_num"></span>of<span id="page_count"></span></li><!-- Zoom In and Out --><li class="navigation__item"><button class="zoom" id="zoom_in"><i class="fas fa-search-plus"></i></button><button class="zoom" id="zoom_out"><i class="fas fa-search-minus"></i></button></li></ul></header><!-- Canvas to place the PDF --><canvas id="canvas" class="canvas__container"></canvas><script src="index.js" type="module"></script></body></html>
Loading the PDF
In your
index.jsfile, add the following line to import the PDF.js library:import * as pdfjsLib from "https://cdn.jsdelivr.net/npm/pdfjs-dist@4.5.136/build/pdf.min.mjs";Set the
workerSrcproperty onpdfjsLib.GlobalWorkerOptionsto point to the worker script. This configuration is essential for PDF.js to operate correctly:pdfjsLib.GlobalWorkerOptions.workerSrc ="https://cdn.jsdelivr.net/npm/pdfjs-dist@4.5.136/build/pdf.worker.min.mjs";In your
index.jsfile, create a variable to hold the PDF document and usedocument.querySelectorto access document object model (DOM) elements. Additionally, set up an object to maintain the initial state of the application:const pdf = "document.pdf";const pageNum = document.querySelector("#page_num");const pageCount = document.querySelector("#page_count");const currentPage = document.querySelector("#current_page");const previousPage = document.querySelector("#prev_page");const nextPage = document.querySelector("#next_page");const zoomIn = document.querySelector("#zoom_in");const zoomOut = document.querySelector("#zoom_out");const initialState = {pdfDoc: null,currentPage: 1,pageCount: 0,zoom: 1,};Pass the name of your PDF document to the
pdfvariable.Use the
pdfjsLib.getDocument(pdf)method to load the PDF file, with thepdfparameter being the path to the PDF file. Then, use the.promise.then()method to handle the promise. The.then()method takes a callback function that will be called when the promise is fulfilled. Here, you can access the PDF file and set theinitialState.pdfDocto the PDF:// Load the document.pdfjsLib.getDocument(pdf).promise.then((data) => {initialState.pdfDoc = data;console.log("pdfDocument", initialState.pdfDoc);pageCount.textContent = initialState.pdfDoc.numPages;renderPage();}).catch((err) => {alert(err.message);});This API makes heavy use of
Promise, a JavaScript feature for handling future values. If you’re not familiar with this pattern, check out the MDN Web Docs(opens in a new tab). After loading the document, set the text content of thepageCountto the number of pages in the document.As you can see, there’s a function called
renderPage(). Use this function to render the current page of your document:
// Render the page.const renderPage = () => { // Load the first page. console.log(initialState.pdfDoc, "pdfDoc"); initialState.pdfDoc.getPage(initialState.currentPage).then((page) => { console.log("page", page);
const canvas = document.querySelector("#canvas"); const ctx = canvas.getContext("2d"); const viewport = page.getViewport({ scale: initialState.zoom, });
canvas.height = viewport.height; canvas.width = viewport.width;
// Render the PDF page into the canvas context. const renderCtx = { canvasContext: ctx, viewport: viewport, };
page.render(renderCtx);
pageNum.textContent = initialState.currentPage; });};- Now that the PDF has been initialized, invoke
getPage()on the document instance. The returnedPromiseresolves with apageobject you can use to render the first page of your document. - To draw something on the canvas, use the
canvas.getContext()method. This method returns a context object you can use to draw on the canvas. - The
getViewport(scale)method returns a viewport object that represents the page at the given scale. - Use the viewport information to set the dimensions of the
<canvas>element, and then start the page renderer with therender(options)API. - At the end, set the text content of the page number to the current page. This will dynamically update the page number.

Navigating through the PDF pages
Until now, you’ve only rendered the first page of your PDF document. Now, you’ll work on making the previous and next icons functional when a user clicks them:
const showPrevPage = () => { if (initialState.pdfDoc === null || initialState.currentPage <= 1) return; initialState.currentPage--; // Render the current page. currentPage.value = initialState.currentPage; renderPage();};
const showNextPage = () => { if ( initialState.pdfDoc === null || initialState.currentPage >= initialState.pdfDoc._pdfInfo.numPages ) return;
initialState.currentPage++; currentPage.value = initialState.currentPage; renderPage();};
// Button events.previousPage.addEventListener("click", showPrevPage);nextPage.addEventListener("click", showNextPage);As you can see, the showPrevPage and showNextPage functions are similar. They both check if the current page is the first or last page, and if it is, they do nothing. Otherwise, they decrement or increment the current page and then render the page.
Displaying a specific page
Here, you can specify which page to render based on a user input. You’re using the keydown event to listen for the Enter key — keypress is deprecated and behaves inconsistently for non-printable keys, so prefer keydown (or keyup) and check event.key === "Enter". When the user presses the Enter key, you’ll get the page number from the currentPage input and check if it’s within the range of PDF pages. If it is, you’ll set the currentPage to the desired page and render the page:
// Keydown event.currentPage.addEventListener("keydown", (event) => { if (initialState.pdfDoc === null) return;
if (event.key === "Enter") { // Get the new page number and render it. let desiredPage = currentPage.valueAsNumber; initialState.currentPage = Math.min( Math.max(desiredPage, 1), initialState.pdfDoc._pdfInfo.numPages, );
currentPage.value = initialState.currentPage; renderPage(); }});For cases when a user types a number that’s either negative or greater than the number of pages, set the currentPage to the first or last page, respectively, and display the page.
Adding a zoom feature to PDF.js
You’re done navigating through the PDF pages. Now, you’ll add the zoom feature:
// Zoom events.zoomIn.addEventListener("click", () => { if (initialState.pdfDoc === null) return; initialState.zoom *= 4 / 3; renderPage();});
zoomOut.addEventListener("click", () => { if (initialState.pdfDoc === null) return; initialState.zoom *= 2 / 3; renderPage();});Similar to how it is with navigation, when the user clicks the zoomIn or zoomOut buttons, you’ll increment or decrement the zoom value and then render the page.
Serving your website
Make sure to copy a PDF file into the folder and rename it to
document.pdf.Install the
servepackage:Terminal window npm install --global serveServe the contents of the current directory:
Terminal window serve -l 8080 .Navigate to
http://localhost:8080to view the website.
Embedding the PDF.js viewer in an HTML window
While the display layer provides fine-grained control over which parts of a PDF document are rendered, there are times when you might prefer a ready-to-use viewer. Luckily, PDF.js has you covered. In this part, you’ll integrate the PDF.js default viewer into the website.
Go back to the
pdfjs-distfolder you downloaded earlier.Copy the entire
web/folder into a new directory.Create a
build/folder inside the new directory and copy thepdf.mjsandpdf.worker.mjsfiles there.Create an
index.htmlfile that will include the viewer via an<iframe>. Locate this file in the root of your project.This enables you to easily embed the viewer into an existing webpage. The viewer is configured via URL parameters, a list of which can be found here(opens in a new tab). For this example, you’ll only configure the source PDF file, and you no longer need the
index.jsfile:<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>PDF.js Example</title></head><body><iframesrc="/web/viewer.html?file=document.pdf"width="1000px"height="1000px"style="border: none"/></body></html>For more advanced features — like saving the PDF document to your web server again — you can start modifying the
viewer.htmlfile provided by PDF.js. You can find theviewer.htmlfile inside theweb/folder.Now, place your PDF file inside the
webdirectory.Run
serve -l 8080 .from the root directory to serve the contents of theindex.htmlfile, and navigate to thehttp://localhost:8080/web/viewer?file=document.pdfURL to view the PDF. Depending on the name of your local PDF file, you can changedocument.pdfto your PDF file name.Your file directory will now look like this:
pdfjs-viewer-example ├── build | └── pdf.mjs | └── pdf.worker.mjs ├── web | └── viewer.html | └── document.pdf | └── ...other files └── index.html 
You can access the demo applications on GitHub(opens in a new tab).
Evaluate the document workflow
The canvas example and the full PDF.js viewer have different capabilities. Mozilla’s architecture overview(opens in a new tab) distinguishes the rendering APIs from the viewer interface. Check the version and configuration you intend to deploy rather than treating this canvas sample as the whole product.
Use representative documents to evaluate these tasks:
- Read and find information — Check rendering, search, navigation, and keyboard access on the browsers and devices your readers use.
- Add feedback — Test the required annotation tools and confirm that exported files retain the feedback in the recipient’s reader.
- Complete a form — Use your actual form fields and validation rules. Check filled values after saving and reopening the PDF.
- Share a review — Define storage, permissions, and synchronization. Embedding a viewer alone doesn’t establish a shared source of truth.
- Sign a document — Distinguish a visible signature mark from certificate-based signing and validation. Verify the required signing workflow separately.
For further evaluation criteria, see PDF.js limitations and workflow requirements.
Building a JavaScript PDF viewer with Nutrient
Nutrient Web SDK provides a viewer interface and APIs for document interaction within your application. Evaluate it when the required task calls for its annotation, form, or editing capabilities. Confirm the features included in your license and deployment.
| Required result | What to evaluate |
|---|---|
| Readers find the right information | Open representative files and test navigation, search, and accessibility in the intended viewer. |
| Reviewers return usable feedback | Add annotations and save or export them. Then inspect the result in the recipient’s reader. |
| Form values survive the handoff | Fill the required fields and reopen the saved document to verify values and appearance. |
| Multiple people see the current review | Test persistence, access control, and concurrent changes with the selected backend. |
| Signed output meets the workflow’s requirements | Check the signing method, certificate requirements, and validation behavior separately. |
PDF.js can suit production applications. Choose between implementations based on these results, deployment requirements, and support needs.
Nutrient’s standalone mode renders documents in the browser with WebAssembly. Browser-side processing doesn’t establish where the application loads or stores files. Check document URLs, exports, backend services, and network requests against your data-handling requirements.
For shared review, see the review persistence architecture guide, which describes Document Engine and Instant synchronization. The loading example below doesn’t configure that architecture.
Use a trial key(opens in a new tab) to evaluate the required features with representative documents. The getting started video(opens in a new tab) provides an introduction to the SDK setup.
Adding Nutrient to your project
Install the @nutrient-sdk/viewer package via npm. If you prefer, you can also download the SDK manually:
npm i @nutrient-sdk/viewerpnpm add @nutrient-sdk/vieweryarn add @nutrient-sdk/viewerTo run Nutrient Web SDK in the browser, copy the required library files (artifacts) to your assets folder:
cp -R ./node_modules/@nutrient-sdk/viewer/dist/ ./assets/Make sure your assets/ folder contains:
nutrient-viewer.js(entry point)- A
nutrient-viewer-lib/directory with the required runtime assets
Integrating into your project
Add the PDF document you want to display (e.g.
document.pdf) to the root of your project. You can use our demo document as an example.Add an empty
<div>element to your HTML where the viewer will mount:<div id="nutrient" style="height: 100vh;"></div>Import the SDK and initialize it using
NutrientViewer.load():
<!DOCTYPE html><html lang="en"> <head> <title>Nutrient PDF Viewer</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div id="nutrient" style="height: 100vh;"></div>
<script type="module"> import "./assets/nutrient-viewer.js";
const baseUrl = `${window.location.protocol}//${window.location.host}/assets/`;
NutrientViewer.load({ container: "#nutrient", document: "document.pdf", baseUrl, }) .then((instance) => { console.log("Nutrient Viewer loaded", instance); }) .catch((error) => { console.error(error.message); }); </script> </body></html>You can serve the application with the serve package like you did for PDF.js.
You should now have our JavaScript PDF viewer up and running in your web application. If you hit any snags, don’t hesitate to reach out to our Support team for help.

If you want to download Nutrient manually or integrate it as a module, you can check out our JavaScript getting started guide.
Verify the saved result
If readers need to return feedback or filled forms, implement an explicit save or export step. For Nutrient, follow the document saving guide. Close the viewer, reopen the saved output, and check that the required changes remain.
Test the same task in the chosen PDF.js implementation. Record which viewer version and configuration produced the result. For shared review, also test access and simultaneous edits; a saved local copy doesn’t establish synchronization.
Conclusion
Choose the viewer that helps readers complete their document task and return the required output. Use the Nutrient demo to assess its tools. Then start a Web SDK trial to test the workflow in your application. Verify the saved document before deciding whether the implementation meets your needs.
Related tutorials: Angular ・ Vue.js ・ React ・ Electron ・ jQuery
Related reading
- How to build a JavaScript PDF viewer with Nutrient — A full-featured JavaScript viewer with a prebuilt UI, annotations, and forms
- Complete guide to PDF.js — In-depth setup, rendering, and customization reference for PDF.js
- JavaScript PDF viewer libraries compared — Five JavaScript PDF viewers ranked side by side to help pick the right one
- Top five document viewers for developers — Comparison of DOCX and PDF viewer libraries beyond PDF.js
- How to choose the best PDF viewer for your business — Business-focused evaluation guide for PDF viewer SDKs
- How to embed a PDF viewer in a website — Six embedding methods compared, from plain HTML tags to a full SDK
- How to extract text from a PDF using JavaScript — Pull text content out of the documents rendered here
FAQ
See our step-by-step migration guide for side-by-side code comparisons covering viewer setup, search, annotations, forms, and more.
PDF.js is an open source JavaScript library from Mozilla that renders PDFs in the browser using HTML5 and canvas, without plugins.
Download the library, include pdf.mjs and pdf.worker.mjs in your project, and then use pdfjsLib.getDocument() to load a PDF and render it on a canvas element.
The choice depends on the document task, saved output, deployment, and support requirements. Test the same representative files with your chosen PDF.js configuration and Nutrient. Confirm licensing and any backend requirements for the features you need.
Nutrient’s standalone mode processes PDFs in the browser. Offline behavior depends on how the application delivers its assets and documents and which services it uses. Verify network requests, storage, licensing, and deployment requirements for the complete application; browser-side rendering alone isn’t a privacy or compliance guarantee.