readTable - the two-line path

truecopy/table

It gets rows and cells out of a file with no configuration at all, plus the field that says what the reading could not vouch for.

import { readTable } from 'truecopy/table';

const { rows, warnings, findings, pages, boundaries, document } = await readTable(file, options?);
Field
rows string[][]: every row of every page, cut into cells
warnings string[]: what could not be vouched for
findings Finding[]: the same doubts, each with a code to act on
pages string[][][]: the same rows kept in their pages, like boundaries
boundaries number[][]: the cut used, one list per page
document the Document, for a reader that needs more than the cells
confidence (number | null)[][][], laid out like pages, when asked for
sums Sum[]: the printed sums that hold, when asked for
proven boolean[][][], laid out like pages, when asked for

options is a TableOptions: everything OpenOptions takes - caps, deadline, workerSrc, pdfjs - plus the five knobs below, which belong to the cut rather than to the file, confidence, which scores the reading, and sums, which checks it against its own totals.

The five knobs of the cut

Neither changes a default, and that is deliberate: a change in how a page is cut never arrives as a new default, it arrives as an option a reader adopts once its own bench is green.

Option Default What it does
rightEdges?: boolean on reads right edges inside a band, cutting flush-right figure columns apart
measuredSpaces?: boolean off spaces the items of a cell as the page printed them, instead of one space apart
pairedParentheses?: boolean off keeps a hanging ) in the cell of the figure it closes
numberEdges?: boolean off cuts a figure from the label printed one space after it
figureEdges?: boolean off parts two columns of figures the cut left in one cell

rightEdges: false restores the cut exactly as it was before right edges were read at all. It exists for compatibility rather than tuning. A finer cut is not free for every reader: one that learned the wider cells - splitting a shared cell itself, on a page printing two tables side by side - loses the row it relied on when a cut lands inside it. Measured on a fund report of that shape, six sections that closed on the wider cells stopped closing on the finer ones, the row carrying one position of each table coming back as neither. It is not a per-document setting to hunt with: a reading that only lands with it off is a reader built on the wider cells, not a better cut.

figureEdges: true parts two figure columns set close together. A bracket printed apart from its figure fills the gap between them, and ( 7,604 ) 3,372 lands in one cell on every row. With the option, a void that comes back ahead of a figure, after a value that was already complete, opens a column, never inside a number printed in groups of three. Measured on 386 tables of annual reports the rule was never tuned on: the cells read wrong and not served fall from 874 to 343, and the cells served or proven by a sum go from 92.00% to 93.84%, right 99.93% of the time against 99.88%. A page it cuts has one column more than it had.

measuredSpaces: true lets the gap on the page decide. An engine breaks a cell into items wherever glyph spacing changes, so one space between all of them turns 1 207 773 393 into 1 2 07 773 393 - a number no reader parses and no check catches, every digit being there in the right order. Measured on that filing: 0,00 point where glyphs touch, 3,6 to 3,8 where a thousands separator or a word space stands, on characters 6,7 points wide. The cut is a quarter of a character, which clears both by a wide margin and, unlike a fixed number of points, does not depend on the font size.

No width is no measurement: a row assembled without geometry - a paste, a CSV, an OCR line handed over whole - keeps its one space between items, having no gaps to read. document.text is not touched either way; the option moves cell text only.

pairedParentheses: true gives a hanging bracket back to its figure. An accounts table sets its figures flush right and hangs the ) of a negative past that edge, so the cut, which reads left edges, hands it to the next column: ( 1,234 beside ) ( 5,678 ). Every digit is still there in the right order, and nothing in findings says the reading is wrong. On, an item goes back to the cell before it when it is only closing brackets, touches that cell’s last item (the same quarter of a character measuredSpaces reads), and that cell has a bracket still open. The column boundaries do not move. Measured on 1 380 tables and pages of published annual reports, each against the structured filing it was printed from: 114 more tables read right, and none that read right before reads wrong after. A column that held nothing but those brackets is left nearly empty and now raises thin-column, which is true. rowToCells and cellsOf take the same flag.

numberEdges: true cuts a quantity from the name printed after it. A portfolio page prints 240.000,00 ABC ARBITRAGE as one run of text, so no geometry sees a gutter inside it. Measured on the portfolio pages of two Luxembourg fund reports, 103 and 43 holdings: every quantity came back welded to its name. With the option, 103 of 103 and 40 of 43 rows read right, and no reading is vouched for wrongly. A number followed by a number is never split, so a figure printed in groups stays whole. A column splits only where the pattern holds at least half of what it carries, so two street numbers in a column of names stay put. A split column has no edge of its own: boundaries stays the cut it was, and the rows of that page are wider than it. The same step is splitLeadingFigures, for rows already cut.

Whatever was dropped, the same two lines

file is a PDF, a table pasted out of one, a CSV, a TSV, an OCR page. One engine reads all of them, because the cut votes on which left edges come back row after row, and that question does not care what measured them. A document only has to say where its fields start.

What was dropped Where a column starts What the reading prints
a PDF the item’s x, in points cut at 100, 290
a table pasted with spaces the character the field starts at cut at characters 7, 22
a file written with a delimiter the field’s index: a CSV lines nothing up cut on the delimiter
prose, or a file that quotes its fields nowhere every row came back whole

Tab, semicolon, pipe and comma, in that order, and only when the count recurs line after line. What makes a delimiter real is what makes a column real.

Two refusals come with that, and both are the point rather than a gap:

  • A file that quotes its fields is not split. A quoted field may hold the delimiter itself, and splitting anyway shifts every column after it. Half-parsing a CSV is exactly the plausible-but-wrong reading this library argues against, so the rows come back whole with a warning.
  • An aligned paste is not read as a CSV because its amounts hold commas. Every French amount does, so counting commas finds exactly one on every line of a pasted statement, and cutting on it would turn 12,40 into two columns. Alignment wins; only a tab overrides it, a tab never being punctuation.

warnings is the whole point

Whoever types “extract tables from pdf” wants rows, and making them write a kindOf and choose thresholds before the first result is twenty minutes most people do not spend. So this is two lines.

What it does not do is return a bare array. A plausible-looking table out of a document that was misread is worse than nothing, because nobody checks a table that looks right. Hand one over with no signal and this library becomes the thing it was written to prevent, and a worse one than the extractors that have spent years tuning their heuristics.

An empty warnings is not a promise. It says nothing looked wrong from the shape of the page. That is a much smaller claim than “this reading is right”, and the distance between the two is what the rest of the library is for.

Every warning is computed without knowing anything about your document:

  • page N carries no text at all: a blank page, a scan, an image;
  • page N shows no column at all: the page is prose, or the cut failed and every row came back whole;
  • column C of page N is filled on only X%: the cut may have invented that column out of a letterhead;
  • the pages disagree on how many columns there are: usually a different table, and joining them makes a third that is neither;
  • column C of page N holds two values on X% of its rows: the cut missed a boundary and two neighbouring columns landed together.

That last one is the opposite failure to a thin column, and the dangerous one. A column the cut never separated is filled on every row, exactly like a good one, so no fill rate can see it: the reading is wrong and silent about being wrong. Read as one figure, one such column produced 97 wrong values out of 162 on a real property schedule.

It only fires when a cell certainly holds two values: nothing but numbers and separators, and every number carrying its own decimal mark. Without that second condition two integers separated by a space are indistinguishable from one number, a space being exactly what French notation puts between thousands - measured, the loose rule fires on 48% of a column that is perfectly well cut, and the strict one on none of it.

findings, for whatever has to act on one

A sentence is for whoever reads it; a code is for whatever acts on it. warnings is derived from findings, so a message and a code can never say different things.

const { findings } = await readTable(file);

// { code, message, page?, column?, shareFilled?, shareDoubled? }
if (findings.some((f) => f.code === 'blank-page')) offerTheScanRoute();

The Doubt codes are the five warnings above: blank-page, no-column, thin-column, merged-column, pages-disagree. Same reason UnreadableDocument names its reason - a program, or an agent, that has to branch on a doubt should not be matching English prose to do it, and a message rewritten for clarity should not break it.

pages, when the flat list is not enough

rows is exactly pages.flat(), and it is the field most readings want. But flattening loses which page a row came from, and some documents cannot be read without it: a page that prints two tables side by side carries two runs of headings, and walking the rows in order alternates between them - a position silently inherits the heading of the other column. pages[i] and boundaries[i] are one page.

confidence, cell by cell

The doubts speak for a page or a column, and a reading that raises none can still carry a wrong figure. confidence: true scores every figure on its own.

import { CONFIDENT_ABOVE } from 'truecopy';
import { readTable } from 'truecopy/table';

const { pages, confidence } = await readTable(file, { confidence: true });

// confidence[i][j][k] is about pages[i][j][k]
const sure = (i, j, k) => (confidence[i][j][k] ?? 0) >= CONFIDENT_ABOVE;

A cell that carries a digit gets a number from 0 to 1, read off the geometry the cell was built from by a model learned once and then frozen. CONFIDENT_ABOVE is the threshold a figure is served as sure at, fixed before the tables it was judged on were collected. Measured on 179 tables from 41 annual reports published outside France: 9,717 of 10,850 figures served as sure, 13 of them wrong (99.87% right, 99.76 to 99.95 across issuers), where 463 of the 10,850 are wrong.

null is no confidence at all, not a low one: every cell without a digit, a page that is not a PDF page, a page with no column, a column the cut merged. With numberEdges none is computed. The option moves no cell and no finding, and it claims nothing past what was measured: annual-report tables rendered to PDF, cut with the default options.

sums, the totals the page prints

A table of accounts checks itself: a total is printed under its terms, or to their right, and a misread cell breaks the equality. sums: true looks for every sum that holds exactly.

import type { Sum } from 'truecopy';
import { readTable } from 'truecopy/table';

const { pages, sums, proven } = await readTable(file, { sums: true });

// proven[i][j][k] is about pages[i][j][k]
const held = (i, j, k) => proven[i][j][k];

Each Sum gives its page, whether it runs along a 'column' or a 'row', its line, the index of its total and of its terms, signs ('printed', or 'free' when a term printed without its sign is subtracted) and agreeing, the parallel lines that hold the same sum at the same places. proven is true for a term or a total of one of them. false is not a doubt: no sum on the page vouches for that cell. A proven subtotal stands for its terms, so a grand total is proven over its subtotals.

The option reads the cells and nothing else, so it works on a PDF, a paste or a CSV alike, and it moves no cell. It does not prove a sign that only a detached dash carries, a figure whose leading group could be a glued note reference, or a total under three digits. A 'free' sum is only believed when a second column, or a third row, holds the same sum on the same lines. Measured once on 386 tables from 87 annual reports gleaned after the rule was set: a sum holds 7,827 of the 21,818 figures and none of them is wrong.

boundaries, and why they are not the page’s own

readTable does not cut on page.columnBoundaries. That one is the spread of x over everything printed (letterhead, address block, footer), and on a real page it proposes columns the table never had: measured, twelve where the table has five.

It uses boundariesFromRecurrence instead: keep only the x that come back row after row, because a real column’s left edge recurs and a word in the middle of a description does not.

boundaries is handed back so you can explain or re-cut the same page against the same lines:

import { explainDocument } from 'truecopy/explain';

const { document, boundaries } = await readTable(file);

console.log(
  explainDocument(document, {
    boundariesOf: (page) => boundaries[page.pageNumber - 1]
  })
);

Without that, the heading and the cells would tell two different stories.

When two lines are not enough

The moment something downstream acts on the rows (a budget, a report, a decision), you want a reading that checks itself rather than one that merely looks fine:

  • findRowAnomalies drops the rows that break the table’s own shape;
  • validate says whether enough well-formed records came back;
  • readDocument refuses to return a reading that contradicts its document.