DEV Community

agebreakco-prog
agebreakco-prog

Posted on

Extracting text from PDF URLs page by page in Node (no Python, no native deps)

AI disclosure: I wrote this article with AI assistance (Claude). The script is a trimmed-down version of an extractor we maintain, and every output below comes from running it on 2026-11-23. We reviewed and tested everything.

If you're feeding documents into search, RAG or a spreadsheet, sooner or later someone hands you a list of PDF links. The usual advice is "use PyMuPDF" or "spin up Apache Tika". Both are fine, but if the rest of your pipeline is JavaScript, you can stay in Node. Mozilla's pdf.js already ships a solid text extractor, and the unpdf package wraps it so it runs in plain Node 20 with no canvas or native build step.

This post builds a small script that:

  • downloads a PDF from a URL and checks that it really is a PDF,
  • extracts text per page (so you can cite "page 7" later),
  • rebuilds readable lines from pdf.js text runs,
  • flags files that are probably scanned images with no text layer.

Why per page?

Joining everything into one string is tempting. Keep the pages anyway:

  • Citations. A RAG answer that says "see page 4" is far more useful than one that points at "the PDF".
  • Chunking. Page breaks are natural chunk boundaries, and you can still merge small pages later.
  • Cost control. Big reports have 300 pages, and you often only need the first 10. A per-page loop lets you stop early.
  • Diagnostics. A page with 0 words in an otherwise normal document is usually a full-page figure or a scanned insert, and you'll want to know that.

The script

npm i unpdf
Enter fullscreen mode Exit fullscreen mode
// pdf-text.mjs: per-page text from PDF URLs. Node 20+, `npm i unpdf`.
import { getDocumentProxy, getMeta } from 'unpdf';

const MAX_BYTES = 50 * 1024 * 1024;

async function download(url) {
  const res = await fetch(url, {
    headers: { accept: 'application/pdf,*/*;q=0.8' },
    signal: AbortSignal.timeout(60_000),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const buf = new Uint8Array(await res.arrayBuffer());
  if (buf.length > MAX_BYTES) throw new Error('too large');
  // Many "PDF links" return an HTML login or cookie page. Check the magic bytes.
  const head = new TextDecoder('latin1').decode(buf.subarray(0, 1024));
  if (!head.includes('%PDF')) {
    throw new Error(`not a PDF (content-type: ${res.headers.get('content-type')})`);
  }
  return buf;
}

// pdf.js gives positioned text runs, not lines. Rebuild lines from hasEOL.
function itemsToText(items) {
  let out = '';
  for (const it of items) {
    if (typeof it.str !== 'string') continue; // marked-content items
    out += it.str;
    if (it.hasEOL) out += '\n';
    else if (it.str && !out.endsWith(' ')) out += ' ';
  }
  return out
    .replace(/[ \t]+\n/g, '\n')
    .replace(/[ \t]{2,}/g, ' ')
    .replace(/\n{3,}/g, '\n\n')
    .trim();
}

const words = (s) => (s.match(/\S+/g) || []).length;

export async function extract(url, maxPages = 0) {
  const pdf = await getDocumentProxy(await download(url));
  const total = pdf.numPages;
  const limit = maxPages > 0 ? Math.min(total, maxPages) : total;
  const pages = [];
  for (let n = 1; n <= limit; n++) {
    const page = await pdf.getPage(n);
    const { items } = await page.getTextContent();
    const text = itemsToText(items);
    pages.push({ page: n, words: words(text), text });
    page.cleanup(); // free per-page memory on big files
  }
  let info = {};
  try { info = (await getMeta(pdf)).info || {}; } catch {}
  const totalWords = pages.reduce((a, p) => a + p.words, 0);
  return {
    url, totalPages: total, pagesRead: pages.length, totalWords,
    title: info.Title || null, producer: info.Producer || null,
    // No text layer: fewer than ~2 words per page means a scan.
    likelyScanned: totalWords < pages.length * 2,
    pages,
  };
}

// CLI: node pdf-text.mjs <url> [<url> ...]
if (import.meta.url === `file://${process.argv[1]}`) {
  for (const url of process.argv.slice(2)) {
    try {
      const r = await extract(url);
      console.log(JSON.stringify({
        ...r,
        pages: r.pages.map((p) => ({ page: p.page, words: p.words, preview: p.text.slice(0, 140) })),
      }, null, 1));
    } catch (e) {
      console.log(JSON.stringify({ url, error: e.message }));
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

A few details are worth calling out.

Check the magic bytes, not the URL. A link ending in .pdf can return a cookie wall, a login page or a 404 page with status 200. Every real PDF has %PDF near the start of the file (the spec allows some junk before it, which is why the script checks the first 1 KB and not just byte 0).

pdf.js gives you text runs, not lines. getTextContent() returns positioned fragments. Each item has a str and a hasEOL flag. Joining with hasEOL as a line break and a space otherwise gives you readable text for most single-column documents. Items without str are marked-content markers, so skip them.

Call page.cleanup(). On long documents, memory otherwise grows with every page you touch.

Real output

I ran it on four links: the "Attention Is All You Need" PDF on arXiv, the W3C's dummy test PDF, the arXiv abstract page for the same paper (a classic mistake: it's HTML) and an old sample-PDF link that has since disappeared.

node pdf-text.mjs https://arxiv.org/pdf/1706.03762
Enter fullscreen mode Exit fullscreen mode

The full paper is 15 pages and 6,527 words, and extraction took 3.7 seconds including the download. Words per page:

1:407 2:645 3:301 4:441 5:579 6:639 7:577 8:609 9:503 10:471 11:448 12:463 13:127 14:159 15:158
Enter fullscreen mode Exit fullscreen mode

The first three pages, trimmed:

{
 "url": "https://arxiv.org/pdf/1706.03762",
 "totalPages": 15,
 "title": null,
 "producer": "pdfTeX-1.40.25",
 "likelyScanned": false,
 "pages": [
  { "page": 1, "words": 407, "preview": "Provided proper attribution is provided, Google hereby grants permission to\nreproduce the tables and figures in this paper solely for use in" },
  { "page": 2, "words": 645, "preview": "1 Introduction\nRecurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks\nin particular, have been firml" },
  { "page": 3, "words": 301, "preview": "Figure 1: The Transformer - model architecture.\nThe Transformer follows this overall architecture using stacked self-attention and point-wis" }
 ]
}
Enter fullscreen mode Exit fullscreen mode

Note "title": null. Plenty of PDFs have empty metadata, so don't rely on the Title field. Take the title from the first lines of page 1 if you need one.

The three other links:

{"url":"https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf","totalPages":1,"totalWords":3,"producer":"OpenOffice.org 2.1","likelyScanned":false}
{"url":"https://arxiv.org/abs/1706.03762","error":"not a PDF (content-type: text/html; charset=utf-8)"}
{"url":"https://www.africau.edu/images/default/sample.pdf","error":"HTTP 404"}
Enter fullscreen mode Exit fullscreen mode

That 404 belongs to a "sample PDF" URL that half the tutorials on the internet still use. Link rot is real, so in a batch job, record the error per URL and move on instead of failing the whole run.

Where it goes wrong

Page 4 of the same paper shows the limits of text extraction:

Scaled Dot-Product Attention Multi-Head Attention
Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several
attention layers running in parallel.
...
queries and keys of dimension d k , and values
Enter fullscreen mode Exit fullscreen mode
  • Math loses its structure. The subscript in dk becomes d k. Formulas come out as loose symbols. If you need equations, look at LaTeX source (arXiv has it) or a dedicated math OCR tool.
  • Figure labels get mixed into the text. "Scaled Dot-Product Attention Multi-Head Attention" is the text inside the diagram, read left to right.
  • Multi-column layouts. pdf.js returns items in content-stream order. For most generated PDFs that is reading order, but some two-column layouts interleave lines from both columns. To fix that you have to sort by the transform x/y coordinates and detect the column gutter, which is more than this script does.
  • Scanned PDFs. There's no text layer, so you get zero or near-zero words. The likelyScanned heuristic (fewer than 2 words per page) catches those, and then you need OCR (Tesseract or a cloud OCR API). Note the dummy file: 3 words on 1 page passes the check, because it really is a text PDF, just a tiny one. Tune the threshold for your documents.
  • Encrypted PDFs with an owner password usually still extract. With a user password they don't, and pdf.js throws a PasswordException that you should catch and report.

Scaling it up

For a few dozen files, run the script in a loop. For thousands, add three things:

  1. Limited concurrency (3 to 5 downloads at a time) and retries with backoff on 429 and 5xx.
  2. A size cap, because someone will eventually hand you a 900 MB scanned archive.
  3. One output row per PDF or per page, plus an error field, so failed links show up in the results instead of killing the job.

If you'd rather not run it yourself

We run the bigger version of this as an Apify actor: PDF to Text Extractor. You give it a list of PDF URLs and get back one row per document or per page, with metadata, word counts and the scanned-PDF flag. Full disclosure: it's ours. It's free to use until December 6, 2026. After that it's pay per use: $2 per 1,000 PDFs plus $0.10 per 1,000 pages, so a 20-page PDF costs about $0.004. Failed downloads aren't charged. It has the same limits as above: no OCR and no math reconstruction.

For a handful of files, though, the script above is all you need.

Top comments (0)