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

> Source: <https://dev.to/agebreakcoprog/extracting-text-from-pdf-urls-page-by-page-in-node-no-python-no-native-deps-45f5>
> Published: 2026-11-23 11:33:14+00:00

**Recommendation:** Validate PDF downloads by scanning the first 1 KB for %PDF rather than the URL or content-type, and flag documents with fewer than about two words per page as likely scans needing OCR.
More in the playbook "Retrieval and RAG": <https://wpnews.pro/playbooks/rag-retrieval>

**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:

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

```
npm i unpdf
js
// 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 }));
    }
  }
}
```

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.

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
```

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
```

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" }
 ]
}
```

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"}
```

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.

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
```

`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.`transform` x/y coordinates and detect the column gutter, which is more than this script does.`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.`PasswordException` that you should catch and report.
For a few dozen files, run the script in a loop. For thousands, add three things:

`429` and `5xx`.` error` field, so failed links show up in the results instead of killing the job.
We run the bigger version of this as an Apify actor: [PDF to Text Extractor](https://apify.com/agebreak/pdf-to-text). 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.
