A table copied out of a PDF viewer and pasted into a spreadsheet usually arrives as one column of text lines. When the source has a "Q3 Total" header merged across three columns, a smarter copy can be worse: the header lands in the first of the three columns and the figures under it line up beneath the wrong labels. Both failures trace back to one gap: ISO 32000-1 defines no table operator
A content stream holds glyphs at coordinates and path segments that may or may not be painted as lines. Only a Tagged PDF can say "this is a table" (§14.8.4.3.4 defines Table, TR, TH and TD), and many report generators never write tags. So the table is rebuilt from geometry, every step a guess with tolerances, and the cells are worth little without metadata that separates a solid guess from a shaky one
Ruled grids and whitespace columns in PDFium Component
PDFium Component runs two detectors over a page and returns their results in one TPdfTables array, sorted top to bottom. TPdf.ExtractTables works on the page in PageNumber; TPdf.ExtractDocumentTables walks every page and links fragments that continue across a page break. Both take a TPdfTableExtractionOptions record, and TPdfTableExtractionOptions.Default turns on DetectRuledTables, DetectWhitespaceTables and DetectContinuations
The ruled detector reads path objects, transforms every segment by the object's matrix into page space, and keeps horizontal and vertical pieces whose drift off the axis stays within RulingTolerance (1 point by default). Strokes are only half the story: with DetectFilledRulings on, thin filled rectangles count as lines and shaded cell boxes contribute their edges, nearby coordinates snap onto shared grid lines, and form XObjects are searched too. That case gets its own walkthrough in reading filled-rectangle borders as table rulings
Rulings that touch or cross are grouped into connected sets, and each set gets its own grid of X and Y positions. That keeps a two-column summary box and a six-column ledger on the same page from fusing into one table full of empty cells. A set becomes a table when its grid has at least MinColumns columns and MinRows rows, both 2 by default
The whitespace detector starts from word boxes. Words that overlap vertically form visual rows, and inside a row a horizontal gap of at least MinColumnGap (12 points) starts a new text group. A run of consecutive rows that each hold MinColumns or more groups becomes a candidate; the run ends where the vertical gap between two rows exceeds MaxRowGapFactor times the taller row's height. Left edges that agree within AlignmentTolerance (3 points) in at least MinRows rows become column anchors, and every row in the run has to reach MinColumns distinct anchors or the candidate is dropped
Two guards keep the whitespace pass honest. Words already inside a ruled table are removed before it runs, so a bordered table never comes back a second time as a borderless copy. And every column boundary has to be a clear vertical corridor through all rows with text on both sides, which justified paragraphs never produce; keeping justified text from reading as a table goes through that rule with examples
A first extraction pass on one page
The page-level call needs an open document and a current page. Setting Active to True opens the file named in FileName, and a file that fails to load leaves Active at False instead of raising, so the listing checks it before going further. Page numbers are 1-based
uses
System.SysUtils, System.IOUtils, PDFium;
procedure ExportPageTables(const PdfPath: string; Page: Integer);
const
ModeName: array [TPdfTableDetectionMode] of string = ('ruled', 'whitespace');
var
Pdf: TPdf;
Options: TPdfTableExtractionOptions;
Tables: TPdfTables;
I: Integer;
begin
Pdf := TPdf.Create(nil);
try
Pdf.FileName := PdfPath;
Pdf.Active := True;
if not Pdf.Active then
raise Exception.CreateFmt('Cannot open %s', [PdfPath]);
Pdf.PageNumber := Page;
Options := TPdfTableExtractionOptions.Default;
Options.HeaderRowCount := 1; // marks the first row of every table
Tables := Pdf.ExtractTables(Options);
for I := 0 to High(Tables) do
begin
Writeln(Format('table %d: %d x %d, %s, confidence %.2f',
[I, Tables[I].RowCount, Tables[I].ColumnCount,
ModeName[Tables[I].DetectionMode], Tables[I].Confidence]));
// TEncoding.UTF8 makes WriteAllText emit a BOM, which Excel
// needs to read the file as UTF-8
TFile.WriteAllText(Format('page%d-table%d.csv', [Page, I]),
string(Tables[I].ToCsv), TEncoding.UTF8);
end;
finally
Pdf.Free;
end;
end;
HeaderRowCount is positional. The first N rows of every table get IsHeader set in their TPdfTableCell records; nothing looks at font weight or shading to decide what a header is. For tables that are pure data, set it to 0, or the first data row comes back flagged as a header
Invalid options, such as both detectors off or MinColumns below 2, raise EPdfError before any work starts, and so does a page that exceeds the MaxWords, MaxCells or MaxTables budget
How are merged cells recovered from a ruled grid?
A page-wide grid misleads here: a header band merged across three columns still has three column slots beneath it, and the merge shows up only as a missing piece of interior line. PDFium Component checks for that locally: for each pair of neighboring base cells, it asks whether some ruling covers the whole stretch of boundary between them, chaining collinear pieces where needed. If nothing covers it, the two cells are joined with union-find, and each joined group becomes one TPdfTableCell whose RowSpan and ColumnSpan give its extent
A merged cell's RowIndex and ColumnIndex point at its top-left corner, with row 0 at the top of the table, and its Bounds cover the whole merged rectangle. Each word goes to the base cell that contains the center of its box, and from there into that cell's merged group. Multi-line cell text keeps CRLF between its lines
One shape is refused. When missing boundaries leave a joined region that is not a rectangle, an L shape left by a border segment the producer never drew for instance, the whole grid is discarded as a ruled table instead of being reported with a span that cannot describe it. Its words stay available to the whitespace pass. Whitespace tables never carry spans at all; every cell there has RowSpan and ColumnSpan equal to 1
A loader that expects a dense matrix, such as a data-frame import, needs every covered position filled. That is a policy decision for the caller, so the table leaves covered positions empty and the expansion is a few lines of your own code:
// Your own helper, not part of the library: copies a spanning cell's
// text into every grid position it covers
function DenseGrid(const Table: TPdfTable): TArray<TArray<string>>;
var
C, R, Col: Integer;
Cell: TPdfTableCell;
begin
SetLength(Result, Table.RowCount);
for R := 0 to Table.RowCount - 1 do
SetLength(Result[R], Table.ColumnCount);
for C := 0 to High(Table.Cells) do
begin
Cell := Table.Cells[C];
for R := Cell.RowIndex to Cell.RowIndex + Cell.RowSpan - 1 do
for Col := Cell.ColumnIndex to Cell.ColumnIndex + Cell.ColumnSpan - 1 do
if (R < Table.RowCount) and (Col < Table.ColumnCount) then
Result[R][Col] := string(Cell.Text);
end;
end;
What does a confidence of 0.88 mean?
TPdfTable.Confidence reads like a probability, but it is built from two inputs you can observe: which detector found the table, and what share of its cells hold text. A ruled table scores 0.88 plus 0.12 times its filled-cell ratio, so it always lands between 0.88 and 1.0. A whitespace table scores 0.58 plus 0.30 times the same ratio, capped at 0.88. Every cell copies the table's value into its own Confidence field
A ruled grid of completely empty boxes, the blank section of an application form, scores exactly 0.88, the same as a whitespace table with every cell filled. And the default MinConfidence of 0.5 sits below both floors, so out of the box it rejects nothing. Suppose an ingestion job raises it to 0.75: every ruled table still passes, and a whitespace table passes once roughly 57 percent of its cells contain text
A single cutoff across both scales is a poor gate for automated pipelines. Check DetectionMode first and apply the threshold to whitespace tables only, where a low fill ratio does hint that the alignment was coincidence. For a ruled table, a low fill ratio far more often means an unfilled form than a misdetection, and whether an empty form belongs in your data is a business rule, which is why the third listing below handles the two modes differently
Linking a table that runs onto the next page
ExtractDocumentTables visits every page, sorts all tables into reading order, and compares each neighboring pair that sits on consecutive pages: the last table on page N against the first table on page N+1. The pair is linked only when it looks like one table interrupted by a page break. Either both fragments sit within ContinuationMargin (36 points) of the page edges, or nothing except running headers and footers lies between them. The second fragment must not open with one cell spanning its full width, since that usually marks a new captioned table. And the column boundaries must agree within twice AlignmentTolerance
Linked fragments share a ContinuationGroup number above zero, and Continuation gives each one's place in the chain as ptcStart, ptcMiddle or ptcEnd. A single ruled row at the top of a page, shorter than MinRows, is kept only when it joins a chain. Because HeaderRowCount is positional, each fragment flags its own first rows as headers, which you have to undo when the producer did not repeat the header. The edge tests, the footer band and stitching a chain into one table are covered in content-aware table continuation across pages
MaxCells and MaxTables apply to the whole run, not page by page, and running out raises EPdfError partway through the document. The method saves PageNumber and restores it in a finally block, so calling it from a viewer leaves the user on the page they were reading
var
Options: TPdfTableExtractionOptions;
Tables: TPdfTables;
Table: TPdfTable;
I: Integer;
begin
Options := TPdfTableExtractionOptions.Default;
Options.MaxCells := 250000; // one budget for every page in the run
try
Tables := Pdf.ExtractDocumentTables(Options);
except
on E: EPdfError do
begin
Writeln('table extraction stopped: ', E.Message);
Exit;
end;
end;
for I := 0 to High(Tables) do
begin
Table := Tables[I];
// 0.82 means at least 80 percent of a whitespace table's cells hold text;
// QueueForReview, AppendToChain and StoreTable are your own routines
if (Table.DetectionMode = ptdmWhitespace) and (Table.Confidence < 0.82) then
QueueForReview(Table)
else if Table.Continuation <> ptcNone then
AppendToChain(Table.ContinuationGroup, Table.ToJson)
else
StoreTable(Table.ToJson);
end;
end;
CSV and JSON output from ToCsv and ToJson
TPdfTable.ToCsv writes one line per row with CRLF separators and quotes every field, doubling any quotation mark inside it, so a cell holding 1,250.00 stays one field. A merged cell's text appears once, at its top-left position, and the positions it covers are written as empty quoted fields
Multi-line cells are the catch. Their CRLF line breaks stay inside the quotes, which RFC 4180 permits, but a loader that splits on line breaks before handling quotes sees a new row mid-cell. Use a real CSV parser. The string also has no byte order mark, and Excel opens a BOM-less UTF-8 CSV with the ANSI code page, which is why the first listing writes through TEncoding.UTF8
TPdfTable.ToJson keeps what CSV drops: page, confidence, mode ("ruled" or "whitespace"), continuation group and position, table bounds, and for each cell its span, header flag, text and bounds. Non-ASCII text is written as-is, control characters are escaped, and numbers always use a dot as the decimal separator, even in a process whose locale formats decimals with a comma. Anything that feeds another system should take JSON: a CSV file has no way to say that its table came from a whitespace match with a third of the cells empty
Tuning for dense reports and scanned pages
When a borderless table comes back missing or split, three whitespace settings are the levers. MinColumnGap (12 points) is the narrowest gap that separates columns; small type with tight gutters needs less. AlignmentTolerance (3 points) is how far left edges may wander and still share a column; it also loosens row grouping. MaxRowGapFactor (3) decides when vertical space ends a table. For rows whose word boxes are about 10 points tall, a table survives blank gaps up to 30 points, and forms printed at 1.5 or double line spacing can need more
The Demo/Delphi/TableExtractionLab project (with C++Builder and Lazarus versions) ships two presets worth copying: "Compact columns" sets MinColumnGap to 4 and AlignmentTolerance to 5, and "Compact + wide rows" also raises MaxRowGapFactor to 6
A scanned page has no text objects, so neither detector has words to place. Add a text layer first, as described in adding a searchable text layer to scanned PDFs. Grid lines in a scan are image pixels, so even a bordered scanned table can only come back as a whitespace table, under that mode's 0.88 confidence ceiling
Rotated text, nested tables and wrapped cells with tall gaps still need a review step; structured text blocks and reading order covers a reader tuned to one document family
Table extraction, structured text and the reflow model all read the same page data in Delphi, C++Builder and Lazarus. Licensing, the full option reference and the other text APIs are on the PDFium Component for Delphi product page