unpdf

Utilities to work with PDFs in Node.js, browser and workers

README

unpdf


A collection of utilities to work with PDFs. Designed specifically for Deno, workers and other nodeless environments.

unpdf ships with a serverless build/redistribution of Mozilla's PDF.js for serverless environments. Apart from some string replacements and mocks, [unenv](https://github.com/unjs/unenv) does the heavy lifting by converting Node.js specific code to be platform-agnostic. See [pdfjs.rollup.config.ts](./pdfjs.rollup.config.ts) for all the details.

This library is also intended as a modern alternative to the unmaintained but still popular [pdf-parse](https://www.npmjs.com/package/pdf-parse).

Features


- 🏗️ Works in Node.js, browser and workers
- 🪭 Includes serverless build of PDF.js ([unpdf/pdfjs](./package.json#L45))
- 💬 Extract text and images from PDFs
- 🧱 Opt-in to legacy PDF.js build
- 💨 Zero dependencies

Installation


Run the following command to add unpdf to your project.

  1. ```bash
  2. # pnpm
  3. pnpm add unpdf

  4. # npm
  5. npm install unpdf

  6. # yarn
  7. yarn add unpdf
  8. ```

Usage


Extract Text From PDF


  1. ```ts
  2. import { extractPDFText, getDocumentProxy } from "unpdf";

  3. // Fetch a PDF file from the web
  4. const buffer = await fetch(
  5.   "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
  6. ).then((res) => res.arrayBuffer());

  7. // Or load it from the filesystem
  8. const buffer = await readFile("./dummy.pdf");

  9. // Load PDF from buffer
  10. const pdf = await getDocumentProxy(new Uint8Array(pdf));
  11. // Extract text from PDF
  12. const { totalPages, text } = await extractPDFText(pdf, { mergePages: true });
  13. ```

Use Legacy Or Custom PDF.js Build


Generally, you don't need to worry about the PDF.js build. unpdf ships with a serverless build of the latest PDF.js version. However, if you want to use an older version or the legacy build, you can define a custom PDF.js module.

  1. ```ts
  2. // Before using any other methods, define the PDF.js module
  3. import { defineUnPDFConfig } from "unpdf";

  4. defineUnPDFConfig({
  5.   // Use the legacy build
  6.   pdfjs: () => import("pdfjs-dist/legacy/build/pdf.js"),
  7. });

  8. // Now, you can use the other methods
  9. // …
  10. ```

Access the PDF.js Module


This will return the resolved PDF.js module. If no build is defined, the serverless build bundled with unpdf will be initialized.

  1. ```ts
  2. import { getResolvedPDFJS } from "unpdf";

  3. const { version } = await getResolvedPDFJS();
  4. ```

Use Serverless PDF.js Build In 🦕 Deno


Instead of using the methods provided by unpdf, you can directly import the serverless PDF.js build in Deno. This is useful if you want to use the PDF.js API directly.

  1. ```ts
  2. import { getDocument } from "https://esm.sh/unpdf/pdfjs";

  3. const data = Deno.readFileSync("dummy.pdf");
  4. const doc = await getDocument(data).promise;

  5. console.log(await doc.getMetadata());

  6. for (let i = 1; i <= doc.numPages; i++) {
  7.   const page = await doc.getPage(i);
  8.   const textContent = await page.getTextContent();
  9.   const contents = textContent.items.map((item) => item.str).join(" ");
  10.   console.log(contents);
  11. }
  12. ```

Config


  1. ```ts
  2. interface UnPDFConfiguration {
  3.   /**
  4.    * By default, UnPDF will use the latest version of PDF.js. If you want to
  5.    * use an older version or the legacy build, set a promise that resolves to
  6.    * the PDF.js module.
  7.    *
  8.    * @example
  9.    * // Use the legacy build
  10.    * () => import('pdfjs-dist/legacy/build/pdf.js')
  11.    */
  12.   pdfjs?: () => Promise<PDFJS>;
  13. }
  14. ```

Methods


defineUnPDFConfig


Define a custom PDF.js module, like the legacy build. Make sure to call this method before using any other methods.

  1. ```ts
  2. function defineUnPDFConfig(config: UnPDFConfiguration): Promise<void>;
  3. ```

getResolvedPDFJS


Returns the resolved PDF.js module. If no build is defined, the latest version will be initialized.

  1. ```ts
  2. function getResolvedPDFJS(): Promise<PDFJS>;
  3. ```

getPDFMeta


  1. ```ts
  2. function getPDFMeta(data: BinaryData | PDFDocumentProxy): Promise<{
  3.   info: Record<string, any>;
  4.   metadata: Record<string, any>;
  5. }>;
  6. ```

extractPDFText


  1. ```ts
  2. function extractPDFText(
  3.   data: BinaryData | PDFDocumentProxy,
  4.   { mergePages }?: { mergePages?: boolean },
  5. ): Promise<{
  6.   totalPages: number;
  7.   text: string | string[];
  8. }>;
  9. ```

getImagesFromPage


  1. ```ts
  2. function getImagesFromPage(
  3.   data: BinaryData | PDFDocumentProxy,
  4.   pageNumber: number,
  5. ): Promise<Uint8ClampedArray[]>;
  6. ```

FAQ


What About Canvas?


The official PDF.js library depends on the optional canvas module, which doesn't work inside worker threads. That's whyunpdf ships with a serverless build of PDF.js that mocks the canvas module.

License


MIT License © 2023-PRESENT Johann Schopplich