truecopy
Extract tables from a PDF in TypeScript, and know when the extraction is wrong.
Turn a document into rows, and refuse the readings you cannot trust. A PDF, a Word or OpenDocument file, a paste, a CSV, an OCR page: one engine reads all of them.

A parser that returns a plausible-looking table from a document it misread is worse than one that returns nothing, because nobody checks a table that looks right. truecopy is the pipeline around whichever reader you write: the door bytes come through, the checks that catch a wrong reading, a way to see what it decided, and a conformance kit that goes red the day the reading stops being honest.
Try it on your worst document, right now
npx -y -p truecopy -p pdfjs-dist truecopy a-statement.pdf
No install, no project, no line of code. The engine is named on the line because it is an optional peer dependency and npm does not fetch one on its own: a project that only ever reads a paste or a CSV never downloads a PDF reader, and for those npx truecopy the-file.csv is the whole command. Left out on a PDF it says no-engine rather than guessing. It prints the cut it made, what each column holds, how often it is filled, and then, on its own, what it could not vouch for.
page 1 - cut at 68, 229, 356, 411, 490
what this reading cannot vouch for:
- column 5 of page 1 is filled on only 2% of its rows - the cut may have invented it
- the pages disagree on how many columns there are (6 on 2, 7 on 1)
npm install truecopy
Rows, in two lines
import { readTable } from 'truecopy';
const { rows, warnings, findings } = await readTable(file);
// rows [['02/05/2026', 'CARTE AMAZON', '12,40'], …]
// warnings ['column 3 of page 2 is filled on only 8% of its rows - the cut may have invented it']
// findings [{ code: 'thin-column', page: 2, column: 3, shareFilled: 0.08, message: '…' }]
No kindOf, no thresholds, no roles. If you only want the cells, destructure rows and go.
file is whatever was dropped. The cut does not care which ruler measured the page, so the same two lines read a PDF, a table pasted out of one, a CSV and a TSV:
| What was dropped |
Where a column starts |
| a PDF |
the item's x, in points |
| a table pasted with spaces |
the character the field starts at |
| a file written with a delimiter |
the field's index: a CSV lines nothing up |
| prose, or a file that quotes its fields |
nowhere: the row comes back whole, and warnings says so |
That last line is the rule and not the exception. A quoted CSV field may hold the delimiter itself, so splitting on it anyway would shift every column after it. truecopy hands the rows back uncut instead, because half-parsing is the failure this library exists to prevent.
explainDocument names the ruler, so a cut is never a bare list of numbers: cut at 100, 290 on a page, cut at characters 7, 22 on a paste, cut on the delimiter on a CSV, where the columns are the fields and their indices would tell you nothing.
The second field is why this is not just another extractor. An empty warnings is not a promise that the reading is right: it means nothing looked wrong from the shape of the page, which is a much smaller claim. Every warning is computed without knowing anything about your document: a page with no columns at all, a column that is almost always empty, pages cut differently from one another, a blank page in the middle.
Those doubts speak for a page or a column. For the figure itself, readTable(file, { confidence: true }) adds confidence, laid out like pages: a number from 0 to 1 for each cell that carries a digit, and a figure at or above CONFIDENT_ABOVE is the one to act on without a second look. On 179 tables from 41 annual reports the model had never seen, that threshold serves 9,717 of 10,850 figures and 13 of them are wrong, where 463 of the 10,850 are. It was measured on annual-report tables rendered to PDF with the default cut and claims nothing past that: null means nothing was measured there, not a low confidence.
findings is that same list with a code on it, plus the page and the column it is about. A person reads the sentence; a program branches on the code, and never on English that could be reworded tomorrow.
When the rows have to be trusted (when something downstream acts on them), the rest of this page is how.
A complete reader that runs, in one file and one command:
node example/read-a-statement.mjs
example/read-a-statement.mjs builds a real PDF, opens it, prints what the reading decided, and drives it through the contract. Nothing in it is stubbed, and it needs no document from you: it makes its own.
See what the reading decided
The first thing you need when a reading comes out wrong is not a better parser. It is knowing which of the three things broke: the document is odd, the cut into columns is wrong, or your rule is wrong. Each calls for a different fix.
import { openDocument, explainDocument } from 'truecopy';
const document = await openDocument(file);
console.log(
explainDocument(document, {
signature: {
kindOf: (cell) => (isDate(cell) ? 'date' : isAmount(cell) ? 'amount' : 'text'),
thresholds: {
date: { share: 0.6, emptyIsAnomalyAbove: 0.7 },
amount: { share: 0.6 },
text: { share: 0.6 }
}
},
roles: [
{ role: 'when', kind: 'date', minimum: 0.6, take: 'best' },
{ role: 'money', kind: 'amount', minimum: 0.6, take: 'each' }
]
})
);
truecopy - statement-2026-05.pdf
pdf, 1 page(s), 6 row(s)
page 1 - cut at 100, 290
3 column(s), 6 row(s)
col kind filled role
0 date 83% when
1 text 100% -
2 amount 100% money
1 02/05/2026 | CARTE 28/04 AMAZON EU> | 12,40
2 03/05/2026 | VIR SEPA LOYER MAI | 750,00
3 05/05/2026 | CARTE 03/05 SNCF CONN> | 68,00
4 09/05/2026 | PRLV EDF | 91,32
5 12/05/2026 | CARTE 11/05 LE BOULAN> | 7,90
6 ! | TOTAL DES DEBITS | 929,62 <- column 0 (date) is empty
Text, not an image: it goes into a terminal, a CI log, a bug report, a test's expected value. It needs no canvas and no headless browser.
No configuration per issuer
The usual way to read a table is to tune settings until one issuer's layout comes out right. It works, and it stops working at the second issuer: every new bank, every new format, every redesign is another block of settings that only its author understands.
truecopy learns the table from the table. A column full of dates is the date column, whatever its header says; a row that breaks what every other row does is a total, a balance, a footer.
import { findRowAnomalies } from 'truecopy/signature';
// Which rows fall outside the signature the table itself sets.
const anomalies = findRowAnomalies(rows, signature);
It reads no label, so it survives an issuer you have never seen. A list of forbidden words only recognises yesterday's documents.
Where that stops, measured
What reads no label is the judgement: which rows belong to the table, which column holds what. The cut is a different problem, and it is the one that still needs help.
Measured on a real bank statement whose header labels were deliberately hidden: the page-wide spread of x proposed twelve columns where the table had five, because it counts the letterhead, the address block and the footer as evidence of where a column starts. Cut on the rows that share the table's shape instead (the ones carrying a date and an amount), it proposed five, and three of the five roles were named from content alone.
boundariesFromRecurrence is the general answer, and readTable uses it: keep only the x that come back row after row, because a real column's left edge recurs and a word inside a description does not. On the statement above it took the cut from twelve columns to seven, and named the rest as thin. Where the page gives you something better to trust (a header row, a rule), boundariesFromAnchors takes it.
And whatever you do, keep the self-check. On that same statement the reading still came back wrong, and the only reason that was visible is that the sum of the rows did not match the balances the document itself declares.
That is the honest shape of this library. It does not promise to read an unknown layout correctly. It promises to tell you when it did not.
Every value knows where it came from
A value you cannot point at is a value nobody can check. Handed a list of figures, a person has to hunt through the document again; handed a place, they jump to it, and that difference is what makes a correction screen used or abandoned.
import { cellsOf, placesOf } from 'truecopy/layout';
const cells = cellsOf(page); // cells[3][1] is what the fourth row holds
const places = placesOf(page); // places[3][1] is where to find it
// { page: 1, x: 430, y: 700, width: 30 }
The two are laid out identically, so they are read together. A cell nothing fell into has no place: null, not a rectangle of nothing. ReviewableRow.where carries the same thing for the rows a person is asked to confirm.
No height, because none is known: a text item carries no height here, and inventing a line spacing would draw a rectangle the document never had.
Notation is not domain
That 1 234,50 and 1,234.50 are the same quantity, that (123,45) is negative and so is 123,45-, that 25/01 is a day before a month here and after it there: none of that says anything about banks or invoices. It says how the page was typeset, and it is the part everybody rewrites and everybody gets wrong once.
import { readNumber, findNumbers, readLeadingDate } from 'truecopy/notation';
readNumber('27800.50'); // 27800.5 - not 2 780 050
readNumber('(123,45)'); // -123.45 - the accounting negative
readNumber("1'234.56"); // 1234.56
// Never starts a match inside another number: a date glued to a figure
// reads as one figure, not as "026 300,00".
findNumbers('30/05/2026 300,00', 2); // [{ value: 300, ... }]
readLeadingDate('25 janv. 2026 GROCERIES', { dateOrder: 'DMY', months });
// { date, length: 13 } - so the caller strips it and keeps the wording
It says null rather than guess. On figures somebody will act upon, a refusal costs a correction and a wrong reading costs a decision.
None of this needs a PDF. truecopy/notation takes strings, so an API field, an HTML scrape or a pasted email gets the same reading as a page, and pdfjs-dist is never loaded. It is the layer worth reaching for before writing a pattern of your own - because the pattern everybody writes instead has a defect nobody sees:
import { accentFree } from 'truecopy/notation';
// `\w` is [A-Za-z0-9_] in JavaScript, whatever the document is written in.
/d[ée]tach\w+/.test('détaché'); // false - the suffix is an accented letter
/d[ée]tach\p{L}*/u.test('détaché'); // true
accentFree('Détaché'); // 'detache' - or fold first and compare plainly
Nothing fails there: the pattern compiles, runs, and returns a plausible fraction of the matches, which then reads as a fact about the documents rather than a defect in the rule.
A refusal you can say in your own language
try {
await openDocument(file);
} catch (error) {
if (error instanceof UnreadableDocument) {
// 'empty' | 'too-big' | 'no-text' | 'too-slow' | 'no-engine' | 'not-opened'
showInYourOwnWords(error.reason);
}
}
The reason is named so the sentence is not. A library that ships only English prose forces an application that speaks anything else to keep its own copy of the door.
no-engine and not-opened are kept apart on purpose, and the difference is not cosmetic: one says install pdfjs-dist, the other says this file will not open, look for its password. Told the wrong one, a person hunts for a lock that does not exist and an agent writes that the document is protected. pdfjs-dist is a peer dependency so that a project reading only pastes and CSV does not download a PDF engine it will never call.
One declaration, two outputs
Write the schema once and get both the check and the record type. A shape declared twice drifts, and the half that drifts silently is always the check.
import { schemaOf, validate, type RecordOf } from 'truecopy/schema';
export const CAREER = schemaOf({
name: 'career-record',
fields: {
year: { format: 'year', minimum: 1930, maximum: 2030, required: true },
quarters: { format: 'integer', minimum: 0, maximum: 4, required: false },
pay: { format: 'number', minimum: 0, required: false }
},
minimumRecords: 5,
key: 'year'
});
export type CareerRow = RecordOf<typeof CAREER>;
// { year: number; quarters: number | null; pay: number | null }
const violation = validate(CAREER, rows);
// null, or { cause: 'too-few-records', conforming: 1, expected: 5 }
The schema is pure data: no accessor, no closure, nothing that does not survive JSON. It can be served, versioned, refined by whoever reads the documents, and swapped for another market without a deploy. What is missing is named; your application writes the sentence in its own voice.
Already declared that row type in Zod, Valibot or ArkType? Do not declare it twice. Any Standard Schema works, and truecopy adds the part a per-record validator cannot know: how many well-formed records make a document.
import { validateWith } from 'truecopy/schema';
validateWith(myZodSchema, rows, { minimumRecords: 5, key: 'year' });
Why refusing matters
The research world arrived at the same place from the other side, and gave it a name: calibrated abstention. Zero Hallucination, by Construction (Raduta et al., 2026) makes it one of six layers of an architecture for enterprise document AI ("the system declines rather than guesses when grounding is insufficient"), paired with an evidence-based confidence that checks what was produced against the source document. Those are refuse and selfCheck, layer for layer.
It stays rare for a reason that is not technical: a benchmark rewards a confident guess and scores an abstention as a miss, so the whole machine is tuned to guess. A deterministic parser has no excuse to inherit that.
The five laws a reader is written to:
- The document checks itself. A bank statement carries
opening + Σ = closing; a career record announces its own total of quarters. Setting your reading against what the document declares is the only check that depends on no layout.
- Refusing beats returning a plausible table. The worst defect is not missing an anomaly; it is inventing twenty-two of them out of a document you misread.
- Counting is not measuring. Running two readings and keeping "the one that finds more rows" always picks the worse: a reader that cuts badly turns footnotes into data.
- The reader proposes, the person confirms. The correction is part of the product, not the recovery path.
- Every quantifier is bounded. These patterns run over a whole document, line by line.
When a model does the reading
A model that turns cells into records fails one visible way - it misses a record - and one invisible way: it returns a plausible value the document never printed. A town deduced from a postcode, a rounded figure, a recomposed date, each reading exactly like a successful extraction. That failure has a deterministic answer, and it does not need a better model: