{"id":13758,"library":"pdfjs-dist","title":"Mozilla PDF.js Distribution","description":"pdfjs-dist is the generic pre-built distribution of Mozilla's PDF.js library, a powerful HTML5-based Portable Document Format (PDF) library designed for parsing and rendering PDFs directly in web browsers. It aims to provide a general-purpose, web standards-based platform for PDF handling. The current stable version is 5.6.205 (as of April 2026), with frequent patch and minor releases, typically on a monthly or bi-monthly cadence, containing improvements for accessibility, performance, annotation editing, and viewer functionalities. Its key differentiators include being an official Mozilla project, its robust support for various PDF features (like annotations, forms, and accessibility), and its ability to operate entirely client-side, making it a popular choice for in-browser PDF display and manipulation without requiring server-side rendering capabilities.","status":"active","version":"5.6.205","language":"javascript","source_language":"en","source_url":"https://github.com/mozilla/pdf.js","tags":["javascript","Mozilla","pdf","pdf.js","typescript"],"install":[{"cmd":"npm install pdfjs-dist","lang":"bash","label":"npm"},{"cmd":"yarn add pdfjs-dist","lang":"bash","label":"yarn"},{"cmd":"pnpm add pdfjs-dist","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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')`.","wrong":"const pdfjsLib = require('pdfjs-dist/build/pdf.mjs');","symbol":"pdfjsLib (namespace import)","correct":"import * as pdfjsLib from 'pdfjs-dist';"},{"note":"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`.","wrong":"import { PDFJS } from 'pdfjs-dist';","symbol":"getDocument","correct":"import { getDocument } from 'pdfjs-dist';"},{"note":"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`.","wrong":"pdfjsLib.workerSrc = '...';","symbol":"GlobalWorkerOptions","correct":"import { GlobalWorkerOptions } from 'pdfjs-dist/build/pdf';"},{"note":"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.","wrong":"pdfjsLib.GlobalWorkerOptions.workerSrc = '/node_modules/pdfjs-dist/build/pdf.worker.min.js';","symbol":"pdf.worker.min.js (worker script)","correct":"pdfjsLib.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.js`;"}],"quickstart":{"code":"import * as pdfjsLib from 'pdfjs-dist';\n\n// IMPORTANT: Configure the worker source. This path must be publicly accessible.\n// Using unpkg or similar CDN is common for browser environments.\npdfjsLib.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.js`;\n\n// For Node.js environments, depending on your setup, you might need a different approach.\n// For example, using `require.resolve` if bundling for Node.js:\n// pdfjsLib.GlobalWorkerOptions.workerSrc = require.resolve('pdfjs-dist/build/pdf.worker.min.js');\n\nasync function loadAndRenderPdf(pdfUrl: string, containerId: string = 'pdf-viewer') {\n  const container = document.getElementById(containerId);\n  if (!container) {\n    console.error(`Container with ID '${containerId}' not found.`);\n    return;\n  }\n  container.innerHTML = ''; // Clear previous content\n\n  try {\n    const loadingTask = pdfjsLib.getDocument(pdfUrl);\n    const pdfDocument = await loadingTask.promise;\n\n    console.log(`PDF loaded: ${pdfDocument.numPages} pages`);\n\n    for (let i = 1; i <= pdfDocument.numPages; i++) {\n      const page = await pdfDocument.getPage(i);\n      const scale = 1.5; // Adjust scale as needed for rendering quality\n      const viewport = page.getViewport({ scale });\n\n      const canvas = document.createElement('canvas');\n      const context = canvas.getContext('2d');\n      if (!context) {\n        throw new Error('Could not get canvas 2D rendering context');\n      }\n\n      canvas.height = viewport.height;\n      canvas.width = viewport.width;\n      canvas.style.display = 'block';\n      canvas.style.margin = '10px auto';\n      canvas.style.border = '1px solid #ccc';\n\n      container.appendChild(canvas);\n\n      const renderContext = {\n        canvasContext: context,\n        viewport: viewport,\n      };\n      await page.render(renderContext).promise;\n      console.log(`Page ${i} rendered to canvas.`);\n    }\n\n  } catch (error) {\n    console.error('Error loading or rendering PDF:', error);\n    container.innerHTML = `<p style=\"color: red;\">Failed to load PDF: ${error instanceof Error ? error.message : String(error)}</p>`;\n  }\n}\n\n// To run this code, you'll need an HTML file like:\n// <!DOCTYPE html>\n// <html lang=\"en\">\n// <head><meta charset=\"UTF-8\"><title>PDF.js Quickstart</title></head>\n// <body><div id=\"pdf-viewer\"></div><script type=\"module\" src=\"./your-script.js\"></script></body>\n// </html>\n// Ensure 'your-script.js' is the compiled output of this TypeScript.\nloadAndRenderPdf('https://raw.githubusercontent.com/mozilla/pdf.js/ba2ddd075de5c0529d8e788c86a1118129202521/web/compressed.tracemonkey-pldi-09.pdf', 'pdf-viewer');\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Thoroughly review the official migration guides on the PDF.js GitHub wiki. For worker-related issues, verify that `GlobalWorkerOptions.workerSrc` is correctly set and points to the appropriate worker file for your specific `pdfjs-dist` version (e.g., `pdf.worker.min.js`).","message":"Major versions of `pdfjs-dist` (e.g., v2 to v3, v3 to v4) often introduce breaking changes, particularly regarding worker initialization, asset loading paths, and API signatures. Always consult the official release notes and migration guides when upgrading across major versions to ensure compatibility.","severity":"breaking","affected_versions":">=2.0"},{"fix":"Copy `pdf.worker.min.js` (and potentially `pdf.worker.mjs` for ESM-only contexts) from `node_modules/pdfjs-dist/build/` to a public static assets folder in your project, then reference this public path in `GlobalWorkerOptions.workerSrc`. Alternatively, use a CDN like `unpkg.com` or `jsdelivr.com`.","message":"The PDF.js worker script (`pdf.worker.min.js`) must be served from a publicly accessible URL and cannot typically be loaded directly from your `node_modules` directory in a browser environment due to security restrictions and typical web server configurations.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Ensure the server hosting the PDF is configured to include appropriate CORS headers (e.g., `Access-Control-Allow-Origin: *` for public PDFs, or `Access-Control-Allow-Origin: your-app-origin.com` for specific origins). The most robust solution is often to serve the PDF from the same origin as your web application.","message":"When loading PDF documents from different origins (i.e., a different domain, protocol, or port than your web application), you are likely to encounter Cross-Origin Resource Sharing (CORS) errors. The server hosting the PDF must explicitly grant permission via `Access-Control-Allow-Origin` HTTP headers.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"For broader compatibility, consider using `pdfjs-dist/legacy/build/pdf.js` and `pdfjs-dist/legacy/build/pdf.worker.js`. Alternatively, configure your bundler (e.g., Webpack, Rollup) to transpile `pdfjs-dist` to an older JavaScript target and include polyfills for `Promise` and `async/await`.","message":"PDF.js relies on modern JavaScript features (e.g., Promises, `async/await`, ES modules). For compatibility with older browsers or legacy environments that lack native support for these features, you may need to use the `legacy/` build variant or ensure your build pipeline transpiles the library and includes necessary polyfills.","severity":"gotcha","affected_versions":">=2.0"}],"env_vars":null,"search_vec":"'2026':64 '5.6.205':60 'abil':113 'access':83,110 'aim':40 'annot':85,107 'april':63 'base':23,50 'bi':77 'bi-month':76 'browser':38,128 'built':12 'cadenc':79 'capabl':139 'choic':124 'client':118 'client-sid':117 'contain':80 'current':56 'design':29 'differenti':92 'direct':35 'display':130 'dist':6 'distribut':3,13 'document':25 'edit':86 'entir':116 'featur':105 'form':108 'format':26 'frequent':66 'function':89 'general':45 'general-purpos':44 'generic':9 'handl':54 'html5':22 'html5-based':21 'improv':81 'in-brows':126 'includ':93 'javascript':140 'key':91 'librari':18,28 'like':106 'make':120 'manipul':132 'minor':69 'month':74,78 'mozilla':1,15,97,141 'offici':96 'oper':115 'pars':31 'patch':67 'pdf':27,53,104,129,142 'pdf.js':2,17,143 'pdfjs':5 'pdfjs-dist':4 'pdfs':34 'perform':84 'platform':51 'popular':123 'portabl':24 'power':20 'pre':11 'pre-built':10 'project':98 'provid':42 'purpos':46 'releas':70 'render':33,138 'requir':134 'robust':100 'server':136 'server-sid':135 'side':119,137 'stabl':57 'standard':49 'standards-bas':48 'support':101 'typescript':144 'typic':71 'various':103 'version':58 'viewer':88 'web':37,47 'without':133","created_at":"2026-04-20T01:56:09.831036+00:00","updated_at":"2026-04-20T01:56:09.831036+00:00","problems":[{"fix":"At 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).","cause":"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.","error":"Uncaught (in promise) Error: The \"workerSrc\" property must be specified."},{"fix":"Ensure 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.","cause":"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.","error":"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [PDF URL]. (Reason: CORS header 'Access-Control-Allow-Origin' missing)."},{"fix":"Verify 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`.","cause":"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).","error":"TypeError: pdfjsLib.getDocument is not a function"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":"https://mozilla.github.io/pdf.js/","github":"https://github.com/mozilla/pdf.js","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/pdfjs-dist","openapi_spec":null,"status_page":null,"smithery":null,"categories":["web-framework"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}