{"id":14806,"library":"pdfjs-lib","title":"PDF.js Library (Legacy `pdfjs-lib` package)","description":"PDF.js is a Portable Document Format (PDF) library built with HTML5, aiming to create a general-purpose, web standards-based platform for parsing and rendering PDFs. The package `pdfjs-lib` with version `0.0.149` (as provided) refers to a very old and effectively abandoned build of the PDF.js library. Its last known publish was over three years ago. The actively maintained and widely used package for consuming Mozilla's PDF.js library is `pdfjs-dist`. The current stable version of `pdfjs-dist` is around `5.6.205`, with a healthy and positive release cadence, often seeing multiple new versions within a few months, and continuous community interaction. Key differentiators include its robust HTML5-based rendering capabilities, cross-browser compatibility, and its role as the underlying technology for Firefox's built-in PDF viewer. It supports rendering PDFs onto HTML5 `<canvas>` elements, including a selectable text layer for search and copy-paste. While `pdfjs-lib` (0.0.149) may still exist on npm, it should be considered deprecated and developers are strongly advised to use `pdfjs-dist` for any new or existing projects.","status":"abandoned","version":"0.0.149","language":"javascript","source_language":"en","source_url":"https://github.com/mozilla/pdfjs-dist","tags":["javascript","Mozilla","pdf","pdf.js","typescript"],"install":[{"cmd":"npm install pdfjs-lib","lang":"bash","label":"npm"},{"cmd":"yarn add pdfjs-lib","lang":"bash","label":"yarn"},{"cmd":"pnpm add pdfjs-lib","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For modern ES module environments, `getDocument` is typically imported from `pdfjs-dist/build/pdf`. The `pdfjs-lib` (0.0.149) package would likely have had a different, CommonJS or global API.","wrong":"const pdfjsLib = require('pdfjs-dist'); // `pdfjs-dist/build/pdf` is the entry point, not root\nconst { getDocument } = pdfjsLib;","symbol":"getDocument","correct":"import { getDocument } from 'pdfjs-dist/build/pdf';"},{"note":"Setting `GlobalWorkerOptions.workerSrc` is crucial for `pdfjs-dist` to offload PDF parsing and rendering to a Web Worker, preventing UI freezes. This must point to the correct URL of the worker script, which can be served from a CDN or a local path.","wrong":"import { GlobalWorkerOptions } from 'pdfjs-dist/build/pdf'; // GlobalWorkerOptions is on the main export object\npdfjsLib.GlobalWorkerOptions.workerSrc = './pdf.worker.js'; // Incorrect worker path, must be correct URL","symbol":"GlobalWorkerOptions","correct":"import * as pdfjsLib from 'pdfjs-dist/build/pdf';\npdfjsLib.GlobalWorkerOptions.workerSrc = `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`;"},{"note":"Modern `pdfjs-dist` uses `.mjs` for its ESM worker scripts. Bundlers like Webpack or Vite often need specific configuration to correctly handle and serve the worker script URL.","wrong":"const worker = require('pdfjs-dist/build/pdf.worker'); // Old CommonJS worker import\npdfjsLib.GlobalWorkerOptions.workerSrc = worker; // May not resolve to correct URL","symbol":"pdf.worker.mjs","correct":"import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.mjs';\npdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;"}],"quickstart":{"code":"import * as pdfjsLib from 'pdfjs-dist/build/pdf';\n\n// Set the workerSrc to enable PDF.js to load the worker script.\n// This is crucial for performance and preventing UI freezes.\n// For production, consider serving pdf.worker.min.mjs from a CDN or your static assets.\npdfjsLib.GlobalWorkerOptions.workerSrc = `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`;\n\nasync function renderPdfToCanvas(pdfUrl, canvasId) {\n  const canvas = document.getElementById(canvasId);\n  if (!canvas) {\n    console.error(`Canvas element with ID '${canvasId}' not found.`);\n    return;\n  }\n  const context = canvas.getContext('2d');\n\n  try {\n    // Asynchronously downloads PDF\n    const loadingTask = pdfjsLib.getDocument(pdfUrl);\n    const pdf = await loadingTask.promise;\n\n    // Fetch the first page\n    const pageNumber = 1;\n    const page = await pdf.getPage(pageNumber);\n\n    const scale = 1.5;\n    const viewport = page.getViewport({ scale });\n\n    // Support HiDPI-screens.\n    const outputScale = window.devicePixelRatio || 1;\n\n    canvas.width = Math.floor(viewport.width * outputScale);\n    canvas.height = Math.floor(viewport.height * outputScale);\n    canvas.style.width = Math.floor(viewport.width) + 'px';\n    canvas.style.height = Math.floor(viewport.height) + 'px';\n\n    const transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null;\n\n    // Render PDF page into canvas context\n    const renderContext = {\n      canvasContext: context,\n      transform,\n      viewport,\n    };\n    await page.render(renderContext).promise;\n    console.log(`Page ${pageNumber} rendered to canvas successfully.`);\n  } catch (error) {\n    console.error('Error rendering PDF:', error);\n  }\n}\n\n// Example usage: Make sure you have a <canvas id=\"pdf-render-canvas\"></canvas> in your HTML\n// And a PDF file accessible at this URL (e.g., in your public folder)\nconst samplePdfUrl = 'https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf';\nrenderPdfToCanvas(samplePdfUrl, 'pdf-render-canvas');\n\n/* Example HTML structure:\n<!DOCTYPE html>\n<html>\n<head>\n  <title>PDF.js Quickstart</title>\n</head>\n<body>\n  <h1>PDF Viewer</h1>\n  <canvas id=\"pdf-render-canvas\" style=\"border: 1px solid black;\"></canvas>\n  <script type=\"module\" src=\"./your-script.js\"></script>\n</body>\n</html>\n*/","lang":"typescript","description":"This quickstart demonstrates how to load a PDF from a URL and render its first page onto an HTML canvas using the modern `pdfjs-dist` package, including the critical Web Worker setup for optimal performance."},"warnings":[{"fix":"Migrate your project to use `pdfjs-dist`. Install it via `npm install pdfjs-dist` and update your import paths and API calls according to `pdfjs-dist`'s current documentation. The API for `pdfjs-dist` has evolved significantly.","message":"The `pdfjs-lib` package (version `0.0.149`) is extremely outdated and effectively abandoned. It is not maintained by the Mozilla PDF.js team and lacks modern features, performance improvements, and security updates found in `pdfjs-dist`. Projects currently using `pdfjs-lib` should migrate to `pdfjs-dist`.","severity":"breaking","affected_versions":"<=0.0.149"},{"fix":"Ensure `workerSrc` points to the correctly bundled or CDN-hosted worker script. For example, `pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`;` or properly configure your bundler (e.g., Webpack, Vite) to copy and provide the correct path to `pdf.worker.mjs`.","message":"The PDF.js library relies heavily on Web Workers for parsing and rendering to prevent UI freezes. The `pdfjsLib.GlobalWorkerOptions.workerSrc` property **must** be set to the correct URL of the `pdf.worker.mjs` (or `pdf.worker.js` for older builds/legacy) file. Incorrectly setting this path is a very common source of errors.","severity":"gotcha","affected_versions":">=1.0.0 (pdfjs-dist)"},{"fix":"Prefer `import` statements in ES module contexts. If you must use CommonJS, consider dynamic imports (`await import('pdfjs-dist')`) or ensure your build setup correctly handles ESM in CJS environments.","message":"Modern versions of `pdfjs-dist` (typically from v2.x onwards) are built as ES Modules (`.mjs`). Directly `require()`-ing them in a CommonJS-only environment without proper transpilation or dynamic imports will lead to errors like 'Cannot use import statement outside a module'.","severity":"gotcha","affected_versions":">=2.0.0 (pdfjs-dist)"},{"fix":"If targeting older browsers, import from `pdfjs-dist/legacy/build/pdf.js` and `pdfjs-dist/legacy/build/pdf.worker.js` instead of the default paths.","message":"For compatibility with older browsers or environments that lack support for modern JavaScript features (e.g., optional chaining, nullish coalescing, private class fields), `pdfjs-dist` provides a `legacy/` folder containing ES5-compatible builds.","severity":"gotcha","affected_versions":">=2.x.x (pdfjs-dist)"},{"fix":"Optimize rendering by using smaller scales, rendering only visible pages, or implementing virtualization. Ensure Web Workers are correctly configured and utilized. Consider alternative libraries like `pdf-lib` for PDF generation or manipulation if `pdfjs-dist`'s rendering capabilities are not sufficient for your use case.","message":"Rendering large or complex PDF documents can consume significant memory and CPU, potentially leading to performance bottlenecks or crashes, especially on less powerful devices or in environments without Web Workers.","severity":"gotcha","affected_versions":">=1.0.0 (pdfjs-dist)"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify the `workerSrc` URL. It must be an accessible HTTP(S) URL or a data URL, not a `file://` URL for browser contexts. Ensure your web server or CDN serves `pdf.worker.min.mjs` with the correct `application/javascript` MIME type. Using a CDN for `workerSrc` is often the easiest solution (e.g., `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`).","cause":"The `pdfjsLib.GlobalWorkerOptions.workerSrc` path is incorrect, inaccessible, or served with the wrong MIME type. This is a common issue with local development or incorrect bundling configurations.","error":"Failed to load worker script at file://.../pdf.worker.js (or similar URL) (reason: cross-origin or MIME type error)"},{"fix":"Ensure your project is configured for ES modules (e.g., `\"type\": \"module\"` in `package.json`, using `.mjs` file extensions, or a bundler like Webpack/Rollup). If using Node.js, dynamically import `pdfjs-dist` using `await import('pdfjs-dist')`. For browser scripts, add `type=\"module\"` to your script tag.","cause":"Attempting to use ES module `import` syntax in a CommonJS (`require`) environment, or in a script tag without `type=\"module\"`. This happens frequently when migrating older projects or misconfiguring bundlers.","error":"Uncaught SyntaxError: Cannot use import statement outside a module"},{"fix":"Ensure you are using `import * as pdfjsLib from 'pdfjs-dist/build/pdf';` for the main library and correctly setting `GlobalWorkerOptions.workerSrc`. For Next.js, ensure dynamic imports are used where appropriate and refer to specific Next.js integration guides for `pdfjs-dist`.","cause":"This error, common in React/Next.js applications, often indicates an incorrect default vs. named import, or a misconfiguration of `pdfjs-dist` that results in an `undefined` or malformed object being imported.","error":"Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object."},{"fix":"Provide the `standardFontDataUrl` option to `pdfjsLib.getDocument()` or configure it globally. This usually points to the `standard_fonts` directory within `pdfjs-dist`. Example: `standardFontDataUrl: path.join(__dirname, 'node_modules/pdfjs-dist/standard_fonts/')`.","cause":"When running `pdfjs-dist` in Node.js environments and dealing with PDFs that require standard fonts, the library needs to know where to find the font data.","error":"Error: Missing `standardFontDataUrl` parameter."}],"ecosystem":"npm"}