Technical Article

Reflow PDF Content to Responsive HTML in Delphi

A contract exported from a word processor with the "tagged PDF" box left unticked still looks structured on screen: a 24-point bold title, numbered clauses, a ruled fee schedule. Convert it to reflowable HTML and the fee schedule comes back as a proper <table>, while the title is a <p> with exactly the same standing as a footnote. That output is correct. ISO 32000-1 §14.8 gives a PDF exactly one place to say "this run of text is a heading", the structure tree, and an untagged file does not have one. Font size and boldness are typesetting choices, and a converter that turns every large bold line into an <h1> will also promote pull quotes, table totals and the company name in the letterhead

The question worth asking of any PDF-to-HTML pipeline, then, is where each heading, list item and table in its output came from, and how far each one can be trusted by a phone layout, a screen reader or a search indexer. Headings and tables give different answers. The export step adds its own choices about line breaks, character encoding and memory

Pipeline diagram of PDFium Component reflow in Delphi, where GetStructuredText feeds either a tagged structure tree or layout reading order into BuildReflowDocument and a self-contained ToHtml export
Every node in the reflow model traces back to the same structured text layer, whether its role was declared by the structure tree or the block fell back to plain layout order

Where headings and lists come from

PDFium Component builds the reflow model with TPdf.BuildReflowDocument, and that method takes every word, block and semantic hint from GetStructuredText, the same structured text layer described in structured text blocks and reading order. There is no second parser and no second text extractor behind it. For each page in the requested range it collects blocks in physical layout order. GetStructuredText has already matched each block against the page's tagged content by overlapping area, and BuildReflowDocument copies the role it found onto the block: H through H6 become headings with their level, LI, Lbl and LBody become list items, Figure becomes a figure whose text is the alternate description, and Caption becomes a caption

Two consequences follow, and both are easy to observe. Block order always follows the page layout, even in a tagged file, so the tags decide what a block is and the geometry decides where it goes. And on a page without tags every block is a paragraph. Headings and lists are never guessed from font size

Every node carries a Source field of type TPdfReadingOrderSource: rosStructure when the role came from the structure tree, rosHeuristic when it came from layout alone. The exported HTML repeats this as data-source="structure" or data-source="inferred" on every element, and the document-level TPdfReflowDocument.Source is rosStructure only when every page in the range was tagged. Tables are always rosHeuristic, because they come from geometric detection and not from Table tags. If a downstream step treats headings as navigation landmarks, check that field first; a tagged document gives you landmarks the author chose

A flat node array instead of an object tree

TPdfReflowDocument.Nodes is a pre-order flattened tree: one dynamic array of TPdfReflowNode records, each holding a ParentIndex and a Depth. Page nodes sit at depth 0 with a parent index of -1. Paragraphs, headings, figures, captions, lists and tables hang off the page at depth 1, list items sit at depth 2 under their list, and table cells reach depth 3 under a row. Consecutive list items share one list node; any other block or a table between them starts a new list

The flat layout is a portability decision. A recursive record containing a dynamic array of itself compiles under Delphi, C++Builder and Free Pascal, yet the three handle recursive managed types differently across a package or DLL boundary. A flat array of plain records behaves the same in all three, and it can be streamed with one for loop and no recursion

uses
  SysUtils, PDFium;

var
  Pdf: TPdf;
  Options: TPdfReflowOptions;
  Doc: TPdfReflowDocument;
  Node: TPdfReflowNode;
  I: Integer;
begin
  Pdf := TPdf.Create(nil);
  try
    Pdf.FileName := 'contract.pdf';
    Pdf.LoadDocument;

    Options := TPdfReflowOptions.Default;   // all pages, tables on, CSS on
    Doc := Pdf.BuildReflowDocument(Options);

    for I := 0 to High(Doc.Nodes) do
    begin
      Node := Doc.Nodes[I];
      case Node.Kind of
        prnkHeading:
          Writeln(Format('%sH%d [%s] %s', [StringOfChar(' ', Node.Depth * 2),
            Node.HeadingLevel,
            BoolToStr(Node.Source = rosStructure, True), Node.Text]));
        prnkTable:
          // on a table node RowSpan/ColumnSpan hold the table's row and column counts
          Writeln(Format('%stable %dx%d, page %d, confidence %.2f',
            [StringOfChar(' ', Node.Depth * 2), Node.RowSpan, Node.ColumnSpan,
             Node.PageNumber, Node.Confidence]));
      end;
    end;

    Writeln(Format('%d node(s), %d table(s), %d character(s), pages %d-%d',
      [Length(Doc.Nodes), Doc.TableCount, Doc.CharacterCount,
       Doc.FirstPage, Doc.LastPage]));
  finally
    Pdf.Free;
  end;
end;

On the untagged contract from the opening, that loop prints no H lines at all and one table line per detected fee schedule. Run it on a tagged copy of the same document and the headings appear with True next to them. FirstPage and LastPage in the options default to 0, which means the first and last page of the document; a range outside the page count raises EPdfError before any page is read

Why does table text not appear twice?

Table detection runs on each page after the structured text has been collected, which means the words inside a table exist twice: once as text blocks, once as cells. Emit both and every table in the HTML is followed by its own contents again as loose paragraphs, which is exactly what a naive "add the tables to the text" merge produces

The model resolves it geometrically. A text block whose bounding box lies at least half inside a detected table's bounds is dropped, and the table node takes its place. Tables are then interleaved with the remaining blocks by vertical position (higher on the page first, with left-to-right as the tie-breaker when the top edges are within half a point), so a table lands between the paragraph above it and the paragraph below it instead of being appended at the end of the page

Diagram of the geometric rule in PDFium Component table detection for Delphi reflow, where a table covering at least half of a text block replaces it so cell text never appears twice
When a detected table covers at least half of a text block, the table node replaces the block so cell text appears exactly once

The half-area threshold has a visible edge. A block that straddles the table border and sits mostly outside it survives intact, so a line of text can occasionally appear both in the last row and in the paragraph that follows. That is the right side to err on. A threshold low enough to remove every overlapping block would also delete body text that merely touches a table's bounding box, and a duplicated line is far easier to notice and forgive than a missing sentence

Detected tables also carry a confidence, and the two detection strategies land in different bands. A table found from ruling lines scores between 0.88 and 1.0, depending on how many of its cells hold text. A table inferred purely from whitespace alignment scores between 0.58 and 0.88. The table node's Confidence holds that score, each cell node repeats it, and the HTML writes it as data-confidence on the <table> element. Tables below TableOptions.MinConfidence (0.5 by default) are never created, and when a table is rejected its words simply stay in the model as ordinary paragraphs

For a search index or a mobile reading view, a wrong table costs little and a correctly detected one is a big improvement, so leave the defaults. For archival conversion, where an invented grid around a two-column address block is worse than no grid, restrict detection to ruled tables:

Options := TPdfReflowOptions.Default;
Options.DetectTables := True;
Options.TableOptions.DetectWhitespaceTables := False; // ruled tables only
Options.TableOptions.MinConfidence := 0.9;            // drop sparse ruled grids too
Options.TableOptions.MaxTables := 200;                // document-wide ceiling
Options.TableOptions.MaxCells := 50000;               // document-wide ceiling

Doc := Pdf.BuildReflowDocument(Options);
if Doc.TableCount = 0 then
  Writeln('No ruled tables; all page text is emitted as paragraphs');

Inside a reflow build, MaxTables and MaxCells are counted across the whole page range, not per page, so a 300-page statement with a ruled table on every page needs MaxTables of at least 300 or the build stops with EPdfError at the first table over the limit. The defaults are 1000 tables and 100000 cells

For the detection side itself, including thin filled rectangles drawn as borders and continuation across pages, see table detection and extraction

Exporting HTML that needs nothing else

TPdfReflowDocument.ToHtml walks the model that has already been built and never touches PDFium again, so exporting the same model twice yields the same string. With FullDocument set (the default) the result is a complete page: doctype, <meta charset="utf-8">, a viewport meta tag, a <title> taken from the document's Title entry (or "PDF document" when that is empty), and a lang attribute from the document's language. With FullDocument off you get a single <div class="pdf-reflow"> fragment to drop into your own template

The optional stylesheet from IncludeCss is one inline <style> block: a 72rem reading column, each PDF page as a white card when IncludePageSections is on, collapsed table borders, and a media query below 40rem that removes the card padding and shrinks table text. There is no script, no web font and no external URL, which is what lets the file sit inside an email, a CHM-style help viewer or a sandboxed browser control. Heading levels outside 1 to 6 are written as h2, header cells become th, and cells with a RowSpan or ColumnSpan above 1 get rowspan and colspan. Turning on IncludeGeometry adds data-left, data-top, data-right and data-bottom in PDF points, which is handy for highlighting a search hit back on the rendered page

PreserveLineBreaks deserves a deliberate choice. A line break inside a PDF paragraph was made for one fixed column width; keep it on a 360-pixel screen and every line wraps twice, the ragged pattern reflow exists to remove. Leave it off (the default) for prose. Turn it on for documents where the break carries meaning, such as addresses, verse or code listings, and it writes <br> instead of a space

For a long document, building the whole page as one WString and then encoding it doubles the memory peak. WriteHtml streams the same markup into a TPdfReportWriter instead, writing ASCII with every non-ASCII character as a numeric character reference, so the bytes are valid regardless of how the receiving side guesses the encoding:

uses
  Classes, SysUtils, PDFium, FPdfAsync, FPdfReport;

procedure ExportReflowHtml(Pdf: TPdf; const FileName: string;
  const Token: IPdfCancellationToken);
var
  Options: TPdfReflowOptions;
  Doc: TPdfReflowDocument;
  Limits: TPdfReportLimits;
  Stream: TFileStream;
  Writer: TPdfReportWriter;
begin
  Options := TPdfReflowOptions.Default;
  Options.MaxNodes := 500000;
  Options.MaxCharacters := 20000000;
  Doc := Pdf.BuildReflowDocument(Options, Token);   // page state is restored afterwards

  Limits := TPdfReportLimits.Default;
  Limits.MaxCharacters := 64 * 1024 * 1024;  // output byte ceiling, 64 MiB maximum
  Limits.MaxItems := Options.MaxNodes;       // one item per node, 1048576 maximum

  Stream := TFileStream.Create(FileName, fmCreate);
  try
    Writer := TPdfReportWriter.Create(Limits, Stream);  // stream stays caller owned
    try
      Doc.WriteHtml(Writer);
    finally
      Writer.Free;
    end;
  finally
    Stream.Free;
  end;
end;

WriteHtml checks more than ToHtml does. It refuses a model with more nodes than Options.MaxNodes, enforces Options.MaxCharacters on the text it writes, limits nesting to the MaxDepth argument (64 by default), and verifies that every ParentIndex points to an earlier node. That last check matters if your code filters or rewrites Nodes before export: an edited array with a forward parent index raises EPdfReportLimit instead of producing markup with mismatched tags

Budgets, cancellation and the current page

A PDF is untrusted input, and a malformed or hostile file can declare thousands of pages of tiny text. BuildReflowDocument checks the character, node, table and cell budgets before each node is added, so a file that exceeds them stops with EPdfError and a message naming the budget ("Reflow node budget exceeded", for example) while memory use is still bounded. Both MaxCharacters and MaxNodes must be positive; the defaults are 10,000,000 characters and 1,000,000 nodes

The optional IPdfCancellationToken is checked before each page, between blocks, before each table and before each table row. Pass the Token of a TPdfCancellationTokenSource owned by your form, call Cancel from the button handler, and the build raises EPdfOperationCancelled at the next of those checkpoints. Catch it separately from EPdfError so a user's cancel is not logged as a broken file. Whichever exception the build ends with, nothing partial is returned; if the failure happens later inside WriteHtml, the destination file holds a truncated page, so delete it in your own exception handler

The page state is the detail GUI code depends on. The build visits every page in the range by moving PageNumber, and a try/finally puts the caller's page back on success, on a budget failure and on cancellation alike. A viewer that starts an export while the user is reading page 340 is still on page 340 when the export returns

Where reflow fits

Reflow output works well as input for search indexing, accessible reading views, phone display and content migration into a CMS. It deliberately drops absolute positioning, exact fonts, vector artwork and page geometry, apart from the optional data-* coordinates. When a job needs the page to look identical, render it; when it needs the words to be readable somewhere else, reflow it

Because headings and lists come only from tags, the quality of the HTML tracks the quality of the tagging upstream. Documents that pass the checks in PDF/UA structure tree validation produce models with real heading hierarchy, and the same tagged content drives the reading features in building an accessible reader

Reflow, structured text, table extraction and rendering all run against the same TPdf object in Delphi, C++Builder and Lazarus; option records, exceptions and the report writer are documented on the PDFium Component for Delphi product page