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
npm install pdf-parseimport { 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();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, ChairpersonEach 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
npm install pdfjs-distIn Node.js, import the legacy build, which does not need a browser:
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);
}COMPANY EXTRACT
Company name Harbor Lane Logistics Ltd
Company number 51-482913-6
Status ActivegetTextContent() 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:
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));
}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:
| File | Result |
|---|---|
| Two-column page | Read column by column, in the right order |
| Hebrew | Plain lines right; lines with numbers or English partly out of order |
| Font without a Unicode map | Gibberish |
| Scan | Empty: 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
legacybuild 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()orpdf.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:
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:
{
"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.