Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
pdfjsLib (namespace import)
✓ import * as pdfjsLib from 'pdfjs-dist';
✗ const pdfjsLib = require('pdfjs-dist/build/pdf.mjs');
This is the most common way to import `pdfjs-dist` in modern browser environments and Node.js with ESM, providing access to `getDocument`, `GlobalWorkerOptions`, and other core utilities. Older CommonJS Node.js projects might need `require('pdfjs-dist/build/pdf')`.
getDocument
✓ import { getDocument } from 'pdfjs-dist';
✗ import { PDFJS } from 'pdfjs-dist';
Named imports are supported for specific functions like `getDocument` from the main entry point. `PDFJS` was a common global object in much older versions of the library but is not the recommended import pattern for modern `pdfjs-dist`.
GlobalWorkerOptions
✓ import { GlobalWorkerOptions } from 'pdfjs-dist/build/pdf';
✗ pdfjsLib.workerSrc = '...';
While `pdfjsLib.GlobalWorkerOptions` works, directly importing `GlobalWorkerOptions` from `pdfjs-dist/build/pdf` can make the purpose of setting the worker path clearer. This object is used to configure critical worker properties like `workerSrc`.
pdf.worker.min.js (worker script)
✓ pdfjsLib.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.js`;
✗ pdfjsLib.GlobalWorkerOptions.workerSrc = '/node_modules/pdfjs-dist/build/pdf.worker.min.js';
This is a *path assignment* for the worker script, not a direct JavaScript import. The `pdf.worker.min.js` file must be publicly accessible via HTTP(S), typically by copying it to your static assets folder or referencing it from a CDN. Directly pointing to `node_modules` in a browser path is incorrect and will fail.
Demonstrates how to load a PDF from a URL, configure the necessary worker script, and render each page of the PDF onto individual HTML canvas elements within a specified container in a browser environment.
import * as pdfjsLib from 'pdfjs-dist';
// IMPORTANT: Configure the worker source. This path must be publicly accessible.
// Using unpkg or similar CDN is common for browser environments.
pdfjsLib.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.js`;
// For Node.js environments, depending on your setup, you might need a different approach.
// For example, using `require.resolve` if bundling for Node.js:
// pdfjsLib.GlobalWorkerOptions.workerSrc = require.resolve('pdfjs-dist/build/pdf.worker.min.js');
async function loadAndRenderPdf(pdfUrl: string, containerId: string = 'pdf-viewer') {
const container = document.getElementById(containerId);
if (!container) {
console.error(`Container with ID '${containerId}' not found.`);
return;
}
container.innerHTML = ''; // Clear previous content
try {
const loadingTask = pdfjsLib.getDocument(pdfUrl);
const pdfDocument = await loadingTask.promise;
console.log(`PDF loaded: ${pdfDocument.numPages} pages`);
for (let i = 1; i <= pdfDocument.numPages; i++) {
const page = await pdfDocument.getPage(i);
const scale = 1.5; // Adjust scale as needed for rendering quality
const viewport = page.getViewport({ scale });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
if (!context) {
throw new Error('Could not get canvas 2D rendering context');
}
canvas.height = viewport.height;
canvas.width = viewport.width;
canvas.style.display = 'block';
canvas.style.margin = '10px auto';
canvas.style.border = '1px solid #ccc';
container.appendChild(canvas);
const renderContext = {
canvasContext: context,
viewport: viewport,
};
await page.render(renderContext).promise;
console.log(`Page ${i} rendered to canvas.`);
}
} catch (error) {
console.error('Error loading or rendering PDF:', error);
container.innerHTML = `<p style="color: red;">Failed to load PDF: ${error instanceof Error ? error.message : String(error)}</p>`;
}
}
// To run this code, you'll need an HTML file like:
// <!DOCTYPE html>
// <html lang="en">
// <head><meta charset="UTF-8"><title>PDF.js Quickstart</title></head>
// <body><div id="pdf-viewer"></div><script type="module" src="./your-script.js"></script></body>
// </html>
// Ensure 'your-script.js' is the compiled output of this TypeScript.
loadAndRenderPdf('https://raw.githubusercontent.com/mozilla/pdf.js/ba2ddd075de5c0529d8e788c86a1118129202521/web/compressed.tracemonkey-pldi-09.pdf', 'pdf-viewer');
Errors
Common errors & fixes
Uncaught (in promise) Error: The "workerSrc" property must be specified.
The path to the PDF.js worker script was not set or was set incorrectly (e.g., to an inaccessible URL) before `pdfjsLib.getDocument` was called.
fixAt the very beginning of your application, before any PDF loading attempts, set `pdfjsLib.GlobalWorkerOptions.workerSrc` to the correct, publicly accessible URL of `pdf.worker.min.js` (e.g., from a CDN or your static assets folder).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [PDF URL]. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
The browser prevented the PDF.js library from fetching a PDF file because it originated from a different domain, and the server hosting the PDF did not provide the necessary CORS (Cross-Origin Resource Sharing) headers.
fixEnsure the server hosting the PDF is configured to send `Access-Control-Allow-Origin` headers that permit requests from your web application's origin. Alternatively, serve the PDF from the same domain as your application.
TypeError: pdfjsLib.getDocument is not a function
This error typically occurs because `pdfjsLib` was imported incorrectly, or the specific `pdfjs-dist` build that includes the `getDocument` function was not loaded, or the environment is incompatible (e.g., attempting browser-specific API usage in a Node.js context without proper setup).
fixVerify that you are using `import * as pdfjsLib from 'pdfjs-dist';` for modern browser/ESM environments. If in Node.js, ensure you are using a build suitable for Node, which might involve different import paths or worker setup, or consider `pdfjs-dist/build/pdf.mjs`.
Audit
Dependencies
No dependency data recorded yet.