Technical Article

Typed PDF Table Extraction in Delphi Across Page Breaks

An invoice register from a German supplier prints 1.234,50 in its amount column. A parser running on the conventions most code assumes, period for decimals and comma for thousands, throws the comma away as a grouping mark and reads the period as the decimal point, so the amount comes back as 1.2345. The same register dates its rows 03.04.2026. Under year-month-day order that string does not parse at all, and once the separators are switched to German, a number parser that sees it before any date parser strips the periods and returns the integer 3042026

The structural traps arrive with the page breaks. For a forty-page register printed as one logical table, header repeated on every page, a per-page reading-order pass returns forty tables, thirty-nine header rows in the middle of the data, and a currency column that slides one position left on every row whose middle cell was blank

Why a PDF page has no table to parse

An untagged PDF page contains positioned text and nothing that says "table". The content stream holds text-showing operators and the matrices that place them (ISO 32000-1 §9.4.3); the ruled grid on screen is separate path painting. The structure types Table, TR, TH and TD exist only in the structure tree of a tagged document (ISO 32000-1 §14.8.4), and most invoices and exported reports are not tagged. Getting a table back is geometric recovery from glyph positions. Scanned pages have no text operators at all, so they need an OCR text layer before any of this applies

HotPDF does that recovery in THotPDF.ExtractLoadedTypedTables. It starts from the same layout analysis that drives structure-order text extraction from a loaded PDF, which groups glyphs into lines and splits lines into cells at the wider gaps. A run of lines counts as a table when at least two consecutive rows have the same number of cells, two or more each, with their left edges lining up; two-column lines of long prose with a wide gutter stay text. That rule is strict on purpose, and its side effect is fragmentation: a block of rows with an empty middle cell has one cell fewer than its neighbors, so one printed table reaches the typed layer as two or three source tables stacked on the page

HotPDF pipeline diagram for ExtractLoadedTypedTables: the layout pass groups extracted glyph baselines into runs, same-page fragments merge on column geometry inside ColumnTolerance, a canonical grid forms per table, continuation across a page break stays conservative, and ExportLoadedTypedTables returns typed cells carrying page provenance, column span and bounds for CSV or JSON
The typed table layer sits above the layout pass to merge the fragments that a same-cell-count run rule inevitably splits apart, then continues tables across pages only when the geometry supports it

Canonical columns, ColumnTolerance and ColumnSpan

ExtractLoadedTypedTables first stitches same-page fragments back together using column geometry alone. Two adjacent source tables on one page merge only when both have at least two columns. The space between the bottom of the upper one and the top of the lower one must be no more than three times ColumnTolerance, and at least two of their column starts must line up within ColumnTolerance. With the default tolerance of 12 user-space units that allows a 36-unit gap, about three lines of 10-point text on 12-point leading. Column starts that fall within tolerance of each other collapse into one canonical column whose position is averaged as fragments join

Each cell is then snapped to the nearest canonical column to the right of the previous cell, and the empty columns it passes over go into ColumnSpan of the cell on their left. A row carrying a part number, a quantity and an amount in a five-column grid comes back with spans of 2, 2 and 1. The quantity sits under its own heading, the amount under the amount heading, and the empty columns are recorded where they are. Switching DetectMergedCells off keeps the column assignment and reports every span as 1. Spans run horizontally only: RowSpan is always 1, so a cell printed across three rows arrives as one cell above two empty positions

HotPDF column diagram showing ExtractLoadedTypedTables snapping each occupied cell of a three-cell row to its nearest canonical column start in a five-column grid, recording ColumnSpan as the distance to the next occupied column instead of shifting cells left, so values stay under the correct headings and the gaps stay visible and reconcilable
Snapping to the nearest canonical column start keeps a row with empty interior cells under the correct headings, and ColumnSpan records the gap instead of letting the currency column slide one place left

Tune the tolerance per document family. An extra column that matches no printed heading, often from indented sub-item rows, means it is too tight; two narrow neighboring columns arriving as one means it is too loose. Compare ColumnCount and the ColumnPositions array of a result against the printed header to tell which. The main flow for the register looks like this

uses
  SysUtils, HPDFDoc;

var
  Pdf: THotPDF;
  Options: THPDFTypedTableExtractionOptions;
  Tables: THPDFTypedTables;
  Info: THPDFTypedTableExtractionInfo;
  Pages: array of Integer;
  I: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    if Pdf.LoadFromFile('register.pdf') <= 0 then
      Exit;
    SetLength(Pages, Pdf.LoadedPageCount);
    for I := 0 to High(Pages) do
      Pages[I] := I;                     // zero-based, ascending
    Options := THPDFTypedTableExtractionOptions.Default;
    Options.DateOrder := ttdoDMY;        // 03.04.2026 is 3 April
    Options.DecimalSeparator := ',';
    Options.ThousandsSeparator := '.';
    Options.ColumnTolerance := 12;       // user-space units
    if Pdf.ExtractLoadedTypedTables(Pages, Options, Tables, Info) then
    begin
      Writeln(Format('%d tables from %d layout fragments, %d repeated header rows',
        [Info.TableCount, Info.SourceTableCount, Info.RepeatedHeaderRowCount]));
      ProcessTables(Tables);             // your own code
    end
    else
      Writeln('Extraction stopped: ', string(Info.Diagnostic));
  finally
    Pdf.Free;
  end;
end;

Each table also carries a Confidence score, and tables under MinimumTableConfidence (0.55 by default) are left out of Tables without an error. To see what the threshold removed on a given file, run once with the option set to 0 and compare the two values of Info.TableCount

What does a cross-page merge require?

ExtractLoadedTypedTables continues a table onto another page only under four conditions: MergeAcrossPages is on, as it is by default; the incoming table starts on the page index immediately after the one where the accumulated table ends; both tables have at least two columns; and at least two canonical column starts align within ColumnTolerance. Only the last table on one page can be continued, and only by the first table on the following page. The "next page" test follows the order of the PageIndices array. Pass 7, 6, 5 and nothing merges, because 6 is not 7 + 1. Pass 3, 9 and 14, and three tables come back however alike their columns look

HotPDF guard diagram for cross-page merging in ExtractLoadedTypedTables: a table continues only when MergeAcrossPages is on, the second table starts on exactly the next page index, and two canonical column starts align inside ColumnTolerance, so a request for pages 3, 9 and 14 stays three tables and FirstPageIndex, LastPageIndex and SourceTableCount leave rejoining to the caller
The consecutive-page condition is the load-bearing one, because callers pass page indices in any order and the alternative is welding unrelated tables into one plausible-looking result that nobody can trust

The consecutive-page rule has a real cost. A genuine continuation that skips a page, such as a register interrupted by a full-page chart or a duplex scan with a blank verso, comes back as two tables, and no option relaxes the rule. The asymmetry is what makes that cost acceptable: a false join yields one plausible table that nothing downstream can question; a missed join yields two tables whose page numbers make the gap obvious, repairable in a few lines with FirstPageIndex, LastPageIndex, ColumnCount and each row's PageIndex

The row with a shape of its own

One input pattern earns a check of its own. A table run needs two or more consecutive rows of the same shape, so a single line item that differs from both neighbors, for example the only row on a page with a blank discount column, does not qualify as a table row and is reported as ordinary text. The rows above and below it form two runs that the same-page merge normally joins across the one-line gap, so the odd row's text ends up in the page's running text. The reasoning holds up: three fragments on one line, alone, look the same as a caption or a signature block. For registers where blank cells are scattered row by row, the vertical step between rows gives it away

uses
  SysUtils, Math, HPDFDoc;

// Reader-side check, not part of the library: report places where the
// step between two rows on the same page is well above the table's
// tightest step, which is where a lone row may have gone to running text
procedure ReportRowGaps(const Table: THPDFTypedTable);
var
  R: Integer;
  Step, MinStep: Double;
begin
  MinStep := MaxDouble;
  for R := 1 to High(Table.Rows) do
    if Table.Rows[R].PageIndex = Table.Rows[R - 1].PageIndex then
    begin
      Step := Table.Rows[R - 1].Top - Table.Rows[R].Top;
      if (Step > 0) and (Step < MinStep) then
        MinStep := Step;
    end;
  if MinStep = MaxDouble then
    Exit;
  for R := 1 to High(Table.Rows) do
    if (Table.Rows[R].PageIndex = Table.Rows[R - 1].PageIndex) and
       (Table.Rows[R - 1].Top - Table.Rows[R].Top > MinStep * 1.8) then
      Writeln(Format('Table %d, page %d: check between rows %d and %d',
        [Table.TableIndex, Table.Rows[R].PageIndex + 1, R - 1, R]));
end;

The 1.8 factor is a starting point, and a header set off by extra space trips it too. When it fires on a body row, the missing line sits between the Bottom of the upper row and the Top of the lower one, in user-space coordinates with y growing upward

Repeated headers are labeled and kept

When a cross-page merge finds that the incoming table opens with the same header text as the accumulated one, compared column by column after trimming and lowercasing, ExtractLoadedTypedTables marks those rows IsHeader and IsRepeatedHeader and appends them in source order. Nothing is deleted, because a CSV import wants the repeats gone while an audit trail wants them kept with their page numbers. DetectRepeatedHeaders turns the comparison off, and Info.RepeatedHeaderRowCount reports how many rows were tagged

A header that changes between pages, typically "Amount (continued)", fails the text comparison. Those rows still come back with IsHeader set, because each page fragment gets its own header detection before the merge, but IsRepeatedHeader stays false, and a filter on IsRepeatedHeader alone lets them through as data. The table's HeaderRowCount covers only the leading block, which makes a tighter filter. Header detection itself goes by cell type, not styling: the header block is every row before the first one that contains a typed value. A body made entirely of text therefore reports HeaderRowCount as 0, and so does a comparative statement whose heading row reads Item, 2025, 2026, because 2025 parses as an integer

var
  T, R, C: Integer;
  Row: THPDFTypedTableRow;
  Cell: THPDFTypedTableCell;
  EuroTotal: Double;
begin
  EuroTotal := 0;
  for T := 0 to High(Tables) do
    for R := 0 to High(Tables[T].Rows) do
    begin
      Row := Tables[T].Rows[R];
      if Row.IsHeader then
      begin
        // the leading block defines the columns; later header rows are
        // skipped whether or not their text matched the first page
        if R < Tables[T].HeaderRowCount then
          DefineColumns(Row);            // your own code
        Continue;
      end;
      AppendRecord(Row);                 // your own code
      for C := 0 to High(Row.Cells) do
      begin
        Cell := Row.Cells[C];
        if (Cell.ValueKind = ttvkCurrency) and (Cell.CurrencyCode = 'EUR') then
          EuroTotal := EuroTotal + Cell.NumberValue;
      end;
    end;
  Writeln(Format('EUR total: %.2f', [EuroTotal]));
end;

Why does 03.04.2026 need a date order?

Type inference runs in a fixed order: boolean, date, percentage, currency, plain number, and whatever is left stays a string. Date before number is what rescues the register from the first paragraph. With DateOrder set to ttdoDMY, 03.04.2026 becomes the date 2026-04-03 before the number parser can strip its periods. A bare 2026 needs a day and month around it to count as a date, so a year column comes back as ttvkInteger. Booleans are the words true, false, yes and no in any letter case, and percentages end in %

Currency needs a leading $, £, ¥ or €, or a three-letter uppercase code followed by a space, as in EUR 1.234,50. The four symbols are recorded in CurrencyCode as USD, GBP, JPY and EUR; a written code is kept as printed. Amounts in accounting parentheses, (1.234,50), come back negative. A symbol written after the amount, the usual layout across much of continental Europe, is outside that rule: 1.234,50 € stays a string, with its text intact for a parser of your own

The separators are where the opening example bites. THPDFTypedTableExtractionOptions.Default ships a period decimal, a comma thousands separator and ttdoYMD, so a German register read with defaults produces exactly that 1.2345. The PDF does not record its locale, and the extractor does not guess one. Set all three options on every call, even where the defaults match, so the assumption is visible in the code. Spaces and no-break spaces are always removed from numbers, which covers the French 1 234,50 with ThousandsSeparator set to #0. A #0 decimal separator, or identical decimal and thousands separators, is rejected up front with ttesInvalidOptions. Every cell keeps its original Text beside NormalizedValue, so a wrong guess can be re-parsed without a second extraction

CSV or JSON: what each export keeps

ExportLoadedTypedTables runs the same extraction and writes it to a stream. CSV writes one line per row with the raw cell Text under each canonical column, empty fields where a span covers a column, and a blank line between tables. Repeated header rows are in it, unmarked, and amounts appear as printed, 1.234,50 included. JSON writes each cell's kind next to its normalized value and raw text, with numbers in period-decimal form and dates as 2026-04-03, plus columnSpan, currencyCode, cell and row confidence, cell bounds, each row's pageIndex, and its header and repeatedHeader flags. A loader that has to drop repeated headers or total amounts should read the JSON. CSV is for handing the table to a person with a spreadsheet

var
  Stream: TFileStream;
  Info: THPDFTypedTableExtractionInfo;
begin
  Stream := TFileStream.Create('register-tables.json', fmCreate);
  try
    if not Pdf.ExportLoadedTypedTables(Pages, ttefJSON, Stream, Options, Info) then
      case Info.Status of
        ttesInvalidOptions: Writeln('Check separators and limits');
        ttesBudgetExceeded: Writeln('Limit reached: ', string(Info.Diagnostic));
        ttesCancelled:      Writeln('Cancelled');
        ttesWriteFailed:    Writeln('Write failed: ', string(Info.Diagnostic));
      else
        Writeln('Extraction failed: ', string(Info.Diagnostic));
      end;
  finally
    Stream.Free;
  end;
end;

Both formats are assembled in memory first, capped by MaxOutputBytes at 256 MiB by default, and copied to the destination only after the whole document has been written. If that copy fails partway, the destination gets back its original bytes, length and position, and Info.Status is ttesWriteFailed. Pages, glyphs per page, tables, rows (one million by default), cells, text characters and output bytes each have their own limit, and going over one ends the call with ttesBudgetExceeded and a diagnostic naming the budget that ran out. For workbooks, the HPDFXLSXExport unit adds HPDFExportLoadedTypedTablesXLSX, which takes the same extraction options

When the PDFs come out of your own reporting stack, the cheapest fix sits upstream: emit tagged tables or keep the source data. For documents you did not produce, start with plain text extraction from a loaded PDF to see what the page text looks like, move to the typed table API once column positions matter, and look at rendering a data table into a new PDF when you control the generating side and can decide how recoverable the output will be

You get the typed table API and its CSV and JSON export with the HotPDF Delphi PDF Component — native Object Pascal for Delphi and C++Builder, no external DLL — and the product page lists the full set of options, status codes and record fields