PDF Engineering · 2026-12-06 · 14 min read
Your PDF Is a 1993 Printer Script Wearing a Trench Coat (4 Fixes, With Code)
Why deleting one word never reflows the page, the four traps that ate a weekend, and the exact qpdf, OCRmyPDF, Playwright, Typst, and Docker commands worth keeping.

Last Friday at 4:52 PM, a Slack message arrived with the confidence of a colleague who has never opened a PDF in a hex editor:
"Hey, tiny favor before the weekend? Can you make this questionnaire look presentable for the client on Monday?"
The file was questionnaire_final_FINAL_v3.pdf. Twenty-six pages, exported from Word, printed, signed, scanned back at 200 DPI, and emailed. Somewhere in that journey a table of contents became a table of regret.
Spoiler: not a tiny favor. Two evenings, one of them a Saturday.
I have now spent an embarrassing amount of time learning how these files actually work, and I want to save you that time. Below: why PDFs behave like they hate you, the four traps I fell into, and the exact code I keep in a folder called pdf-hell.
Everything here runs on my laptop, and the numbers are measured.
First, why editing a PDF feels like defusing a bomb
Because a PDF is not a document. It is a printer instruction script from 1993, wearing a trench coat and claiming to be a document.
Word, Google Docs, and HTML think in flows. You type a sentence, the paragraph grows, everything below it moves down. A PDF has no concept of "below". It has a canvas, and things painted on that canvas at absolute coordinates.
Open any PDF in a text editor and the useful part looks like this:
BT
/F1 11 Tf
1 0 0 -1 72 720 Tm
(Total Due: 14,800 USD) Tj
ET
Read it as instructions to a literal intern:
BT/ET: begin and end a text object./F1 11 Tf: use font F1 at 11 points.1 0 0 -1 72 720 Tm: set the text matrix. That-1flips the Y axis, because PDF measures from the bottom-left corner while everything else in your life measures from the top-left. The72 720is the pen position in points.(Total Due: 14,800 USD) Tj: paint these characters at that spot.
Now delete the number. The characters disappear. Nothing else moves, because there is no "else". There is no paragraph, no line height, no flow. There is a hole where the number was, and the rest of the page is still exactly where the printer put it in 1993.
That explains most of why traditional PDF editing feels fragile.
The part nobody tells you: the text is usually compressed
Those instructions are stored in a content stream, and content streams are zlib-compressed with /Filter /FlateDecode. So you cannot just read the file.
Two ways in. The clean one, if you have qpdf:
brew install qpdf
qpdf --qdf --object-streams=disable invoice.pdf invoice.qdf.pdf
--qdf rewrites the file in readable form and --object-streams=disable unpacks the object streams, so any editor will show you the operators. The result is bigger. That is the point.
The no-install way, which is what I actually ran while writing this, on a 39 KB PDF I had just generated:
import re, zlib
data = open("report.pdf", "rb").read()
for m in re.finditer(rb"stream\r?\n", data):
raw = data[m.end():data.find(b"endstream", m.end())]
try:
dec = zlib.decompress(raw)
except zlib.error:
continue
if b"BT" in dec:
print(dec.decode("latin-1")[:400])
break
Real output from that run, trimmed:
BT 0 Tr/f0 24 Tf 1 0 0 -1 0 0 Tm[(\000\001\000\002\000\003\000\004 ...)]TJ
ET
Q
EMC/Span<</MCID 1>>BDC
q 1 0 0 -1 45.354332 736.50415 cm/c0 cs 0.43137255 scn
1 0 0 -1 again: the flip matrix, now with a translation. That is the renderer converting from a top-left layout engine to PDF's bottom-left coordinate space.
And (\000\001\000\002\000\003 ...): those are not letters. They are glyph indices into a subset font. The letter "Q" is glyph 1 in this particular embedded subset, so it is stored as byte \001. This is why copying text out of some PDFs gives you □ □ □, and why "just extract the text" is a harder problem than it sounds. The file does not contain the string "Q4 Platform Release Notes" anywhere. It contains a sequence of numbers that a specific embedded font knows how to draw.
Once you accept that a PDF is a drawing, every workaround below makes sense. None of them are editing a document. They are all either (a) adding a fake text layer, (b) converting the drawing back into a flow, or (c) throwing the drawing away and building a new one.
Trap 1: "I'll just convert it to Word and fix it there"
For a clean, single-column, text-based PDF, pdf2docx does a genuinely decent job:
from pdf2docx import Converter
cv = Converter("proposal.pdf")
cv.convert("proposal.docx", start=0, end=None)
cv.close()
Ten pages of single-column prose with real headings? It comes back recognisable. Fix the fonts, done in five minutes.
Now feed it the documents that actually land in your inbox.

Two columns. The converter reads left to right across the full page width, because there is nothing in the file that says "column". A sidebar headline gets glued to the end of a body paragraph from the other column. You get sentences like "Revenue grew 14% quarter over quarter OUR MISSION" and then you spend twenty minutes separating them by hand.
Nested tables. The outer table becomes a table. The inner ones become a stack of paragraphs, or a single row with 40 columns, depending on the day. Merged cells are a coin flip. Row heights collapse because Word recalculates them from the text, and the original heights were a drawing decision, not a text decision.
A scanned page. This is the fun one. There is no text on that page, only an image. So the converter faithfully inserts one giant picture into your Word file, and now you have a document where page 7 is a photo of a page and page 8 is editable text. Word's own importer and the Google Docs uploader behave the same way, because they are solving the same unsolvable problem.
When it still works: single column, real text layer, no fancy tables, under about fifteen pages, and you only need to change wording. Then pdf2docx is faster than everything else in this article. I use it maybe twice a month for exactly that.
When it doesn't: anything with a layout you care about. Conversion is lossy in the design dimension even when it is lossless in the text dimension. You will spend longer repairing the damage than rebuilding.
Trap 2: expecting OCR to make a scan look good
If someone sends you a crooked scan and you want to hit Cmd+F or copy a clause out of it, OCRmyPDF is the best free tool that exists. One command:
ocrmypdf \
--deskew \
--clean \
--rotate-pages \
--force-ocr \
scanned_lease.pdf \
clean_lease.pdf
Here is what it actually printed on a four-page scanned lease, unedited, because the numbers are the interesting part:
Scanning contents ━━━━━━━━━━━━━━━━━━━━ 100% 4/4 0:00:00
INFO Start processing 4 pages concurrently (4 workers, unpaper=enabled)
INFO 1 [tesseract] Detected skew angle: -2.41° → deskewing + unpaper clean
INFO 2 [tesseract] Detected skew angle: -1.87° → deskewing + unpaper clean
INFO 3 [tesseract] Detected skew angle: +0.94° → deskewing + unpaper clean
INFO 4 [tesseract] Detected skew angle: -1.12° → deskewing + unpaper clean
OCR ━━━━━━━━━━━━━━━━━━ 100% 4/4 0:00:06
INFO Postprocessing...
PDF/A conversion ━━━━━━━━━━━━━━━━━━ 100% 4/4 0:00:01
Linearizing ━━━━━━━━━━━━━━━━━━ 100% 1/1 0:00:00
INFO Image optimization ratio: 1.42x · savings: 29.6%
INFO Output file is a PDF/A-2B (as expected)
$ ls -lh scanned_lease.pdf clean_lease.pdf
-rw-r--r-- 1 dev staff 4.8M scanned_lease.pdf # image-only scan
-rw-r--r-- 1 dev staff 3.4M clean_lease.pdf # searchable PDF/A-2B (layout unchanged)
Four pages, six seconds of OCR, 29.6% smaller, valid PDF/A-2B. Every page got its own skew estimate: -2.41°, -1.87°, +0.94°, -1.12°. That is a scanner fed by hand, corrected per page instead of globally.

And then the line that matters, sitting quietly in my own ls output:
# searchable PDF/A-2B (layout unchanged)
layout unchanged.
That is not a bug report. It is the design goal. OCRmyPDF draws an invisible text layer underneath the original pixels so the page becomes searchable, selectable, and archivable. It does not move a single element, because moving elements would destroy the evidentiary value of a scan. If a contract says what it says because of where the signature sits, you do not want a tool quietly re-laying out the page.
So after OCR, your 2009 fax is a searchable 2009 fax: same grey cast, same coffee ring, same crooked margins. Useful, not a makeover.
The batch version, because one file is never one file
Every time I OCR one file, there are forty more in a folder. This is the script I actually use. It runs four at a time, writes a per-file log, and skips anything already done, so you can Ctrl+C and rerun without redoing work:
#!/usr/bin/env bash
# batch-ocr.sh — OCR every PDF in a folder, resumable.
# usage: ./batch-ocr.sh ./scans ./scans/ocr
set -euo pipefail
in_dir="${1:?usage: batch-ocr.sh <in-dir> [out-dir]}"
out_dir="${2:-$in_dir/ocr}"
jobs="${JOBS:-4}"
mkdir -p "$out_dir"
find "$in_dir" -maxdepth 1 -type f -iname '*.pdf' -print0 \
| xargs -0 -P "$jobs" -I{} bash -c '
src="$1"; out="$2"
base="$(basename "${src%.*}")"
dst="$out/${base}-ocr.pdf"
if [ -f "$dst" ]; then echo "skip $base"; exit 0; fi
if ocrmypdf --deskew --clean --rotate-pages --skip-text \
--output-type pdfa-2 "$src" "$dst" 2>"$out/${base}.log"; then
echo "ok $base"
else
echo "FAIL $base (see ${base}.log)"; rm -f "$dst"
fi
' _ {} "$out_dir"
Three details that took me a while to get right:
--skip-textinstead of--force-ocr. If a PDF already has a text layer on some pages (mixed exports are common),--force-ocrrasterises and re-OCRs everything, which is slow and slightly degrades the image.--skip-textleaves good pages alone.-P "$jobs"onxargs, not aforloop. Tesseract is happy to use multiple cores, but four concurrent files beat one file using four threads, because I/O and PDF parsing overlap.- Per-file stderr into
$base.log. When one file fails at page 37, you want the traceback, not a wall of interleaved output from four processes.
Trap 3: "I'm a web dev, I'll rebuild it in HTML and print to PDF"
This is the right answer and also a trap, because headless Chrome finds new ways to hurt you.
The setup that finally stopped biting me:
// generate-pdf.mjs — node generate-pdf.mjs
import { chromium } from "playwright-core";
import { pathToFileURL } from "node:url";
const browser = await chromium.launch({ channel: "chrome" });
const page = await browser.newPage();
await page.goto(pathToFileURL("report.html").href, {
waitUntil: "networkidle", // webfonts and images have landed
});
// Chrome resolves fonts asynchronously. Skip this and page 1 renders in
// Times while page 2 renders in Inter, which is a fun bug to explain.
await page.evaluate(() => document.fonts.ready);
await page.pdf({
path: "out.pdf",
printBackground: true, // otherwise every background colour vanishes
preferCSSPageSize: true, // trust @page size and margins, not format
displayHeaderFooter: true,
headerTemplate: `<div style="font:8px Arial;color:#8a94a0;width:100%;padding:0 16mm;">
CloudPulse · Q4 Release Notes
</div>`,
footerTemplate: `<div style="font:8px Arial;color:#8a94a0;width:100%;padding:0 16mm;
display:flex;justify-content:space-between;">
<span>Confidential</span>
<span>Page <span class="pageNumber"></span> of <span class="totalPages"></span></span>
</div>`,
});
await browser.close();
Four of those options are load-bearing:
waitUntil: "networkidle"waits until there have been no network requests for 500 ms. With"load"you get a PDF where the logo is a broken image icon, roughly one run in five.document.fonts.readyis the one nobody knows about.page.pdf()can run before the font swap finishes, and Chrome will happily fall back to a system serif for the first page only. If your PDF has two typefaces and you only specified one, this is why.printBackground: trueis required or Chrome drops background colours and borders. You will then spend an hour adding-webkit-print-color-adjust: exactand wondering why it changed nothing. Both are needed, for different reasons: one tells Chrome to paint backgrounds at all, the other stops the print path from optimising them away.preferCSSPageSize: truemakes the@pagerule authoritative. Without it, Chrome uses theformatoption and your carefully measured 16 mm margins become whatever the default is.
The CSS that actually matters
@page {
size: A4;
margin: 18mm 16mm 20mm;
}
* {
/* Without this, Chrome strips background colours in the print path */
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
/* Stop Chrome from slicing a table row or a card in half */
.card, tr, blockquote, figure {
break-inside: avoid;
page-break-inside: avoid;
}
/* Repeat table headers on every page */
thead { display: table-header-group; }
tfoot { display: table-footer-group; }
/* Do not leave a heading stranded at the bottom of a page */
h1, h2, h3 { break-after: avoid; }
/* Three lines minimum before a break, so you never get a widow */
p { orphans: 3; widows: 3; }
Even with all of that, the print path finds creative ways to hurt your feelings:

The one that cost me the most time: break-inside: avoid on a <tr> is honoured, but only if the row is not taller than a page. A 40-row table wrapped in a single <tbody> with break-inside: avoid on the tbody will simply overflow and clip. Put the rule on the row, never on the body.
I timed it, because "Chrome is slow" is not a number
Same one-page report, same content, both ways, one M-series Mac, five runs each, median shown:
| Metric | Chrome 158 page.pdf() | Typst 0.15.1 |
|---|---|---|
| Wall time (median of 5) | 2.20 s | 0.17 s |
| Fastest / slowest | 1.88 s / 2.29 s | 0.16 s / 0.17 s |
| Peak RSS, whole command | ~200 MB | ~42 MB |
| Output size | 72 KB | 39 KB |
| Cold start | browser launch and teardown dominate | none, single native binary |
| Fonts | whatever the OS has installed | embedded or fetched, deterministic |
| Page breaks | you fight CSS | computed by the layout engine |
About 12x slower and 5x heavier for the same page. And this is the best case for Chrome: one page, no images, no webfonts to download. Add a 3 MB hero image and a Google Font and the gap widens.
Peak RSS is what /usr/bin/time -l reports for the whole command. Chrome forks helper processes, so the real total footprint is higher than 200 MB. Typst at 42 MB is one process and one binary.
Chrome is not wrong, it is just expensive per run. If your data already lives in a React app, page.pdf() costs nothing to adopt. Two hundred nightly invoices take 7 minutes in Chrome and 34 seconds in Typst.
The Typst version, which is one file and no browser
// release-notes.typ
#set page(
paper: "a4",
margin: (x: 16mm, y: 18mm),
footer: context [
#set text(size: 8pt, fill: luma(130))
CloudPulse Systems Inc — Platform Engineering
#h(1fr)
Page #counter(page).display() of #counter(page).final().first()
],
)
#set text(font: ("Helvetica Neue", "Arial"), size: 10.5pt, fill: luma(20))
#set par(justify: true, leading: 0.62em)
#show heading.where(level: 2): it => block(above: 1.4em, below: 0.6em)[
#set text(size: 13pt, weight: "semibold")
#it.body
#v(-0.45em)
#line(length: 100%, stroke: 0.6pt + luma(210))
]
#let kpi(value, label) = block(
inset: 9pt,
stroke: 0.6pt + luma(226),
radius: 4pt,
[#text(size: 17pt, weight: "bold")[#value] #linebreak()
#text(size: 9pt, fill: luma(110))[#label]],
)
#text(size: 24pt, weight: "bold")[Q4 Platform Release Notes]
#v(2pt)
#text(size: 9pt, fill: luma(110))[v3.8 · Core Platform Team · 12 December 2026]
#v(12pt)
#grid(columns: (1fr, 1fr, 1fr), gutter: 8pt,
kpi[42%][faster queries],
kpi[SAML 2.0][enterprise SSO],
kpi[v3][REST and webhook],
)
== Endpoint performance
#table(
columns: (1fr, auto, auto, auto, 1fr),
inset: (x: 6pt, y: 5pt),
stroke: (x, y) => if y == 0 { 1pt + luma(180) } else { 0.4pt + luma(232) },
fill: (x, y) => if y == 0 { luma(244) },
align: (left, right, right, right, left),
table.header([*Endpoint*], [*p50*], [*p99*], [*Delta*], [*Scope*]),
[GET /v2/invoices/:id], [148 ms], [610 ms], [-73.6%], [Global edge],
[POST /v2/payments/capture], [96 ms], [310 ms], [-41.2%], [US-East],
[POST /v2/webhooks/verify], [12 ms], [44 ms], [-8.0%], [Dead-letter queue],
)
typst compile release-notes.typ out.pdf
No browser, no @media print, no 200 MB of Chromium. Page breaks are the layout engine's job. counter(page).final() gives you "Page 2 of 3" without a second pass.
The catch: Typst is not HTML, so your React components do not port. For a one-off report, rewriting it in a new markup language is a day you will not get back. If you generate the same document shape daily, it pays for itself in a week.
Trap 4: compliance says the file cannot leave the building
Never upload client contracts, medical records, or payroll to a random free converter. Obvious when written down, surprisingly common at 6 PM on a Friday.
Stirling-PDF is the answer I keep giving, because it is one container and it covers redaction, signing, OCR, splitting, merging, compression, and about sixty other operations. This compose file is the one I run, based on their docs, with analytics turned off and a memory ceiling so it cannot eat the whole machine:
services:
stirling-pdf:
image: docker.stirlingpdf.com/stirlingtools/stirling-pdf:latest
container_name: stirling-pdf
ports:
- "8080:8080"
volumes:
- ./stirling/configs:/configs
- ./stirling/logs:/logs
- ./stirling/tessdata:/usr/share/tessdata
- ./stirling/pipeline:/pipeline
- ./stirling/storage:/storage
environment:
SYSTEM_ENABLEANALYTICS: "false" # no PostHog, no Scarf pixel
LANGS: en_GB
mem_limit: 4g
restart: unless-stopped
SYSTEM_ENABLEANALYTICS=false is the one that matters for a bank or a hospital. Their docs are explicit that document contents are never sent, but the server does report version, OS, CPU, memory, and operation counts to PostHog's EU servers. Turning it off is one line. Do it before someone in security asks.
mem_limit: 4g because OCR on a 300-page scan will otherwise grow until the kernel stops it, and a container that gets OOM-killed mid-merge is a bad afternoon.
Then drive it from a script instead of clicking:
# merge two files, returns one PDF
curl -sS -X POST http://localhost:8080/api/v1/general/merge-pdfs \
-F "[email protected]" \
-F "[email protected]" \
-o merged.pdf
# OCR a scan, keep the original images
curl -sS -X POST http://localhost:8080/api/v1/misc/ocr-pdf \
-F "[email protected]" \
-F "languages=eng" \
-F "deskew=true" \
-o scan-ocr.pdf
Endpoint names move between releases, so check /v1/api-docs on your own instance before you hardcode them in a pipeline. The shape stays the same: multipart upload in, PDF bytes out.
The honest cost: you now operate a service. A container, a volume for the Tesseract data, backups, and someone who remembers to pull a new image. If you do three PDFs a year, use a desktop tool instead.
The 30-second decision tree
One typo in a document that is otherwise fine?
└── PDF editor, desktop, offline. Do not rebuild anything.
Scanned, and you need Cmd+F or a legal archive copy?
└── OCRmyPDF. It says "layout unchanged" and means it.
File can't leave the network, or you need 400 operations?
└── Stirling-PDF in Docker, analytics off.
Data already in your app, generating the same doc repeatedly?
└── Typst if you can own the template, Playwright if you can't.
Looks like a 2009 fax and the words are all correct?
└── This is a layout problem, not a file problem. Keep reading.
That last branch is the one that took me years to name. Every tool above is a toolbox for content: find the text, remove the field, fix the skew, merge the files. None of them touch how the page reads. Which is why a technically perfect 26-page questionnaire can still get skimmed, ignored, and answered with "can you send a cleaner version".
The gap: the file is fixed, the layout is still 2009
Full disclosure: this section covers RedesignPDF, the tool we build. The four tools above are in our actual workflow and we have said what each one is good and bad at.
The job that none of them do is: take a document whose words and numbers are correct, and give it a layout a reader can scan. Not rewrite it. Not convert it to broken Word text boxes. Rebuild the page visually around the same content.
Here is what that looks like on four documents that have nothing in common except being hard to read.
Case 1: an incident postmortem that got printed and annotated

The original is a four-page draft printed at 03:14, marked up with a highlighter and a red pen, then scanned back at an angle. The p99 checkout latency spike to 1,840 ms and the 4.82% error rate survive only because somebody circled them.
The rebuild keeps #INC-4092, the DO NOT DISTRIBUTE header, and every row of the latency table, and drops the scan artifacts. The failing rows get colour, the handwritten FIX BEFORE LAUNCH note becomes a callout beside the terminal output, and the three remediation steps stop being handwriting.
Case 2: a principal architect's resume

Marcus Vance has 10+ years in distributed systems, and the original buries that under black boxes, highlighter on every section heading, star ratings for skills, and a typo in the word latency.
The rebuild keeps every metric ($1.8M/yr cut from AWS, p99 from 420 ms to 38 ms, 85,000 TPS, 99.995% uptime) and swaps the stars for percentage bars and the boxes for a timeline. Same sentences, including the 12TB/day ingestion line.
Case 3: a $23,760 quote that arrived creased

This one is a scan of a printed quote: #QT-2026-884 from Apex Systems Engineering to Meridian Logistics, folded twice, shot under a desk lamp, with a blue stamp sitting on top of the header.
The rebuild puts the total in a full-width band, keeps all seven line items and the 40/40/20 schedule verbatim ($9,504 on signing, $9,504 at UAT sign-off, $4,752 at launch), and keeps the red URGENT APPROVED stamp, because that stamp is the point of the document.
Case 4: release notes that were never meant to be a document

The original is what Cmd+P on a Confluence page produces: the left sidebar comes along, the breadcrumb is clipped at the right edge, and the wiki URL is printed in the footer.
The rebuild keeps the module table, all four impact numbers (18% faster close, 62% less login dropoff, 3.4x throughput, 99.98% delivery), and the breaking-change notice about /v1/tokens, and gives the three charts room to breathe.
Where this stops being the right answer
The honest edges:
- Handwriting. A scanned form with a pen signature over printed text will confuse visual redraw. Check those pages by hand.
- Dense small type in non-Latin scripts. 7pt Japanese or Chinese footnotes occasionally come back with a wrong glyph. Proofread before sending.
- Merged table cells and footnotes. Complex tables can shift by a few points between source and rebuild. Compare side by side, especially for anything with money in it.
- It is not a word processor. If the job is rewriting long paragraphs, use a desktop editor. A visual rebuild pass fixes layout and scan artifacts, not prose.
- Compliance and pricing. The cleanup utilities (deskew, pure black and white, searchable OCR) run locally in your browser at 0 credits. The visual AI layout pass runs on our servers at 2 credits per page (preview is free online, with 2 free AI pages before sign-in plus 3 more after sign-in, 4+6 credits total). If your policy forbids cloud uploads, stay on Stirling-PDF plus OCRmyPDF and skip this section entirely.
The 80/20 version
If you read nothing else, this table is the whole article:
| Situation | Tool | Why |
|---|---|---|
| One wrong date in a 40-page contract | Desktop PDF editor | Editing one object is not a rebuild |
| 300 scanned pages, need search | ocrmypdf --deskew --clean | 6 seconds per 4 pages, archive-grade |
| 400 files, same operation | Stirling-PDF + curl | Runs on your hardware, scriptable |
| Invoices every night from a DB | Typst, or Playwright if you must | 12x faster, 5x lighter, deterministic |
| Correct words, unreadable layout | RedesignPDF visual rebuild | The only branch that changes how it reads |
| Scanned, ugly, needs signing | OCR, then rebuild, then sign | Backwards wastes an hour |
The last row is the one people get wrong: running OCR on a page after you rebuilt it means doing the expensive step twice.
Have a PDF whose words are right but the layout still looks like 2009?
Drop your PDF or scan below. Preview is free online, browser-local cleanup tools cost 0 credits, and AI layout redraw includes 2+3 free pages (4+6 credits).