# Read, render and split PDFs

Use two sets of command-line tools, called from your station as in [Call a command-line tool from a station](/docs/guides/run-command-line-tools).

| Job | Tool | Command |
|---|---|---|
| Count the pages | `pdfinfo` (poppler-utils) | `pdfinfo invoice.pdf`, then read the `Pages:` line |
| Read the text layer | `pdftotext` (poppler-utils) | `pdftotext -q invoice.pdf -` prints the text |
| Render pages as images | `pdftoppm` (poppler-utils) | `pdftoppm -png -r 150 invoice.pdf out/page` writes `page-1.png`, `page-2.png`… |
| Split, or turn pages upright | `qpdf` | `qpdf --empty --pages bundle.pdf 3-5 -- part.pdf` |

```bash
brew install poppler qpdf                   # macOS
sudo apt-get install poppler-utils qpdf     # Debian, Ubuntu
```

Give each tool a path env var (`PDFTOTEXT_PATH`, `PDFINFO_PATH`, `PDFTOPPM_PATH`, `QPDF_PATH`) that defaults to its name.

## Read a PDF: the text layer first, images for a scan

A PDF made by software carries its text, and `pdftotext` returns it exactly and fast. A scan carries only pictures, so `pdftotext` returns nothing or a few stray characters. Decide by counting what came back:

```js
const page_count = await pageCount(pdf_path);          // pdfinfo
const text = await extractText(pdf_path);              // pdftotext -q <pdf> -

if (text.replace(/\s+/g, '').length >= config.text_layer_min_chars) {
  return { read_as: 'text', page_count, text };
}
const image_paths = await renderPages(pdf_path, render_dir, { dpi: config.image_dpi });   // pdftoppm
return { read_as: 'images', page_count, image_paths: image_paths.slice(0, config.max_vision_pages) };
```

- **Put the thresholds in the station's config.** Current factories use `text_layer_min_chars: 20` and `image_dpi: 150`, and send a model at most 15 to 30 pages.
- **Record how the document was read** (`read_as`) in the file the station writes, so a reviewer knows whether the model read text or looked at pictures.
- **List the rendered files; don't build their names.** `pdftoppm` pads the page number to the width of the page count (`page-01.png` once there are ten pages), so read the folder and sort by the number in each name.
- **Keep images small enough for the model.** A phone photo can be over a model's size limit. Cap the long side, for example at 2000 px with `pdftoppm -scale-to 2000`, or with [sharp](https://sharp.pixelplumbing.com) for a photo that isn't a PDF.

Text and `.csv` files are read as they are, and an image file goes to the model like a rendered page. Don't guess at a file you can't read, such as a spreadsheet or an archive: route it to a sub-bin a person handles, or fail it with a reason.

## Keep the renders out of the workpiece

Page images are scratch. They're big and the next station doesn't need them. Write them to a folder beside the bins, not in the workpiece, and delete it whatever happens:

```js
const render_dir = path.join(bin('IN1'), '.render', workpiece_id);   // temp/stations/IN1/.render/inv-1001
try {
  const doc = await readDocument(pdf_path, render_dir);
  // send doc.text or doc.image_paths to the model, write extraction.json
} finally {
  fs.rmSync(render_dir, { recursive: true, force: true });
}
```

`.render` holds no `pointer.json`, so the conveyor and the watchers never take it for work. See [Where a station keeps its data](/docs/guides/keep-station-data).

## Split a bundle into documents

A scanned bundle often holds several documents. First find the page range of each one: current factories ask a model for ranges such as `1-2`, `3` and `4-6`. Then cut with `qpdf`:

```js
const QPDF = process.env.QPDF_PATH || 'qpdf';

export async function splitByRanges(pdf_path, ranges, out_dir) {
  const problems = validateRanges(ranges, await pageCount(pdf_path));
  if (problems.length > 0) throw new Error(`invalid_range: ${problems.join('; ')}`);

  fs.mkdirSync(out_dir, { recursive: true });
  const stem = path.basename(pdf_path, '.pdf');
  const parts = [];
  for (const range of ranges) {
    const out_path = path.join(out_dir, `${stem}_${range}.pdf`);
    try {
      await execa(QPDF, ['--deterministic-id', '--warning-exit-0', '--empty', '--pages', pdf_path, range, '--', out_path]);
    } catch (err) {
      throw new Error(`split_failed: ${range} of ${path.basename(pdf_path)}: ${err.stderr || err.message}`);
    }
    parts.push({ page_range: range, path: out_path });
  }
  return parts;
}
```

| Rule | Why |
|---|---|
| Check every range before cutting: `N` or `N-M`, within the page count, no overlaps | A model's ranges can be wrong. Throwing before any file is written leaves nothing half-split. |
| Allow gaps | A blank separator page can be left out |
| `--empty --pages <file> <range> --` | Starts a new, empty PDF and copies in only those pages |
| `--deterministic-id` | Without it, `qpdf` stamps a random id into each file. With it, splitting the same bundle again gives byte-identical parts, so a check by hash knows them as duplicates. |
| `--warning-exit-0` | `qpdf` repairs many damaged PDFs and then exits with code 3, "succeeded with warnings". The parts are fine, so don't fail on it. |

Each part then becomes a workpiece of its own: see [Splitting work](/docs/method/splitting-work).

## Turn pages upright

`--rotate=+<angle>:<pages>` turns pages clockwise. Write the result as a new file next to the original, never over it:

```js
await execa(QPDF, ['--warning-exit-0', '--deterministic-id', '--rotate=+90:1,3', '--rotate=+270:5', pdf_path, upright_path]);
```

## Next

- [Code first, the model for judgment](/docs/method/code-before-the-model): what to ask the model once it has the text or the images, and how to check its answer
- [Write a station that processes workpieces](/docs/guides/process-workpieces): the loop these calls run inside
- [Find out why a workpiece failed](/docs/guides/handle-failures): reading a `split_failed` or `pdftotext_failed` error
