How to extract text from a PDF in Node.js

Updated · Tested with Node.js 22, pdf-parse 2.4.5, pdfjs-dist 6.5.438

In short

Use pdf-parse for the whole text in one call, or pdfjs-dist (Mozilla's PDF.js) when you need each piece of text with its position. In Node.js, import pdfjs-dist from its legacy build and pass the file as a Uint8Array. Neither reads scanned pages, which contain no text.

Two packages cover almost every need in Node.js: pdf-parse for a one-call answer, and pdfjs-dist, Mozilla's PDF.js, when you want control over every piece of text. pdf-parse is built on PDF.js, so the two read files the same way. The examples use company-extract.pdf and run as ES modules on Node.js 22.

pdf-parse: one call

Shell
npm install pdf-parse
JavaScript
import { readFile } from "node:fs/promises";
import { PDFParse } from "pdf-parse";

const parser = new PDFParse({ data: await readFile("company-extract.pdf") });
const result = await parser.getText();
console.log(result.text);
await parser.destroy();
Output
COMPANY EXTRACT
Company name 	Harbor Lane Logistics Ltd
Company number 	51-482913-6
Status 	Active
Registered 	14 March 2019
Registered office 	22 Quay Street, Haifa
Share capital 	1,250.50
Directors
Dana Levi, Chairperson

Each label and its value are on one line, separated by a tab where the page has a gap between two columns. That makes them easy to split.

If you are following an older tutorial: version 2 of pdf-parse changed its interface. The old const pdf = require("pdf-parse"); pdf(buffer) no longer works; create a PDFParse object as above.

pdfjs-dist: every piece of text

Shell
npm install pdfjs-dist

In Node.js, import the legacy build, which does not need a browser:

JavaScript
import { readFile } from "node:fs/promises";
import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";

const data = new Uint8Array(await readFile("company-extract.pdf"));
const pdf = await getDocument({ data }).promise;

for (let number = 1; number <= pdf.numPages; number++) {
  const page = await pdf.getPage(number);
  const content = await page.getTextContent();
  let text = "";
  for (const item of content.items) {
    text += item.str + (item.hasEOL ? "\n" : "");
  }
  console.log(text);
}
Output
COMPANY EXTRACT
Company name Harbor Lane Logistics Ltd
Company number 51-482913-6
Status Active

getTextContent() returns the text in pieces. Each item has its string in str and a flag, hasEOL, that says whether a line ends after it. Join the pieces yourself, as the loop does. Note the Uint8Array: PDF.js does not accept a Node.js Buffer directly.

Text with positions

Every item also carries its position in transform, a list of six numbers whose last two are x and y. PDF.js reports y from the bottom of the page, so subtract it from the page height to measure from the top:

JavaScript
import { readFile } from "node:fs/promises";
import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";

const data = new Uint8Array(await readFile("company-extract.pdf"));
const pdf = await getDocument({ data }).promise;
const page = await pdf.getPage(1);
const { height } = page.getViewport({ scale: 1 });
const content = await page.getTextContent();

for (const item of content.items.filter((i) => i.str.trim()).slice(1, 5)) {
  const [, , , , x, y] = item.transform;
  console.log(x.toFixed(1), (height - y).toFixed(1), item.width.toFixed(1), JSON.stringify(item.str));
}
Output
68.4 140.8 81.6 "Company name"
204.4 140.8 131.5 "Harbor Lane Logistics Ltd"
68.4 168.1 93.5 "Company number"
204.4 168.1 63.7 "51-482913-6"

The label starts at x = 68 and its value at x = 204, on the same line (y = 140.8). That is all you need to pair labels with values. Text with coordinates explains the units.

What to expect on harder files

We ran pdfjs-dist on the other samples from these articles. pdf-parse uses the same engine, so expect the same from it:

FileResult
Two-column pageRead column by column, in the right order
HebrewPlain lines right; lines with numbers or English partly out of order
Font without a Unicode mapGibberish
ScanEmpty: there is no text in the file

A 200-page file took about 0.4 seconds with either package, including starting Node.js.

In Next.js and serverless functions

Both packages are plain JavaScript and run in a route handler or a function. Three things trip people up:

  • Read PDFs on the server, in a route handler or a server action, not in a client component.
  • Import the legacy build of pdfjs-dist. The default build expects browser features.
  • Watch memory on large files: PDF.js holds the whole document in memory. Call parser.destroy() or pdf.destroy() when you are done.

Text in reading order from an API

Neither package reads a scanned page, and both put Hebrew lines that contain numbers or English partly out of order. 100sands reads PDFs and HTML files that contain text, with lines in reading order in every language. It is one request, using the fetch and FormData built into Node.js:

JavaScript
import { readFile } from "node:fs/promises";

const form = new FormData();
form.append("file", new Blob([await readFile("company-extract.pdf")]), "company-extract.pdf");

const response = await fetch("https://api.100sands.com/v1/text", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.SANDS_API_KEY}` },
  body: form,
});
if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
const { pages, text } = await response.json();
console.log(pages, text);

The response has this shape:

JSON
{
  "pages": 1,
  "text": "COMPANY EXTRACT\nCompany name\tHarbor Lane Logistics Ltd\nCompany number\t51-482913-6\nStatus\tActive\n..."
}

A label and its value set apart on one line are separated by a tab, and pages by a form feed (\f). 100sands does not read scans either: for company-scan.pdf the call fails with status 422 and the code NO_TEXT_IN_FILE, which is why the code above checks response.ok. Word and Excel files are refused with 415.

Questions

What is the best npm package to extract text from a PDF?

pdf-parse for a one-call answer, and pdfjs-dist when you need positions or control over how lines are joined. pdf-parse is built on PDF.js, so both read files the same way.

Why does my old pdf-parse code not work?

Version 2 changed the interface. Calling the module as a function, pdf(buffer), no longer works. Create an object with new PDFParse({ data: buffer }) and call its getText() method.

How do I use PDF.js in Node.js or Next.js?

Import getDocument from pdfjs-dist/legacy/build/pdf.mjs, which does not need a browser, and run it on the server: in a route handler or a server action, not in a client component.

Can Node.js extract text from a scanned PDF?

Not with these packages. A scan is a picture, and both return an empty result. Use an OCR engine or an OCR service for scanned pages.

Try it on your own documents

A free plan every month, no credit card. See the PDF to text API.

Start free