PDFium Delphi Component Docs

FPdfTextShaping unit

Unit: FPdfTextShaping
Shapes bidirectional Unicode text into visual glyph runs for TPdf.AddShapedText, with bounded input and output sizes and an extensible shaper base class

Workflow

APIPurpose
ShapePdfText(Text, FontName, FontSize, Direction, out Shaped)Shapes text with the configured backend or platform default and default resource limits
PdfShapedTextSelection(Shaped, FirstGlyph, LastGlyph, out TextStart, TextLength)Maps a visual glyph range across the returned runs to the minimal logical UTF-16 span, expanding partial selections to complete clusters and reporting unmapped glyphs as zero-length spans
TPdfTextShaper.ShapeAbstract shaping contract for custom engines that return glyph identifiers, clusters, visual runs, advances, and selected font data
TPdfTextShaper.ShapeSpan(Text, Start, Count, FontName, FontSize, Options, out Shaped)Shapes the complete text and returns only [Start, Start + Count) as a standalone shape whose text and clusters are span-relative, so a cursive-joining word keeps the forms its neighbours give it
TPdfTextShaper.SupportsSpanShapingReports whether the backend keeps that context; a backend that reports False leaves callers on whole-token boundaries
TPdfTextShaper.SupportsVerticalShapingReports whether the backend returns vertical metrics; a backend that reports False rejects a Vertical request instead of shaping horizontally
TPdfUniscribeTextShaper.ShapeUses usp10.dll to itemize, shape, place, and visually reorder text runs
TPdfTextShapingOptions.DefaultReturns automatic direction with limits of 1,000,000 characters, 2,000,000 glyphs, and 100,000 runs
ConfigureTextShaper(Shaper)Installs the shaping backend the unit uses, replacing the built-in one for the rest of the process; the unit takes ownership of the instance
ClearTextShaperRemoves an installed backend and returns to the platform default
ActiveTextShaperThe backend currently in use, or nil when no shaper is available on this platform
ActiveTextShaperNameName the active backend reports, for logging and for telling one deployment from another

Version 3.337.0 reconstructs the selected Windows TrueType Collection face as a standalone sfnt by reading its individual GDI tables, rebuilding offsets/checksums and omitting stale DSIG data. Glyph IDs and selected table contents remain intact; the font reader bounds input/output to 64 MiB and paragraph editing retains its stricter font/embedding limits

Public types

TypeDescription
EPdfTextShapingErrorException raised for invalid inputs, resource-limit violations, font-data failures, or shaping-engine errors
TPdfTextDirectionptdAuto, ptdLeftToRight, ptdRightToLeft, ptdResolvedLeftToRight, ptdResolvedRightToLeft or ptdTopToBottom; the original ordinals 0, 1 and 2 remain unchanged and the later values are append-only
TPdfShapedGlyphOne glyph with GlyphID, Advance, OffsetX, OffsetY, and zero-based UTF-16 ClusterStart/ClusterLength; continuation glyphs can have a zero-length logical span
TPdfShapedGlyphsDynamic array of TPdfShapedGlyph records
TPdfShapedRunOne run with zero-based UTF-16 TextStart/TextLength, VisualX, Width, BidiLevel, IsRightToLeft, and Glyphs
TPdfShapedRunsDynamic array of TPdfShapedRun records with explicit VisualX and bidi metadata; the built-in backends retain logical item order in the array
TPdfShapedTextSource Text, selected FontName, FontSize, embedded FontData, shaped Runs, total Width, GlyphCount, and LogicalCharacterCount measured in UTF-16 code units
TPdfTextShapingOptionsDirection, MaxCharacters, MaxGlyphs and MaxRuns resource limits
TPdfTextShaperAbstract base class for a caller-provided shaping implementation
TPdfUniscribeTextShaperBuilt-in Windows implementation of TPdfTextShaper

Remarks

Already resolved directions since v3.339.0

ptdLeftToRight and ptdRightToLeft set a paragraph base direction and retain ordinary bidi resolution inside the text. The appended resolved modes accept a logical run whose direction has already been determined and keep every character in that direction, including numbers and opposing strong characters

Uniscribe uses the initial direction override with level 0 or 1. HarfBuzz receives uniform levels 0 or 1 before script segmentation and per-buffer shaping, without resolving the substring as another paragraph. Both expose consistent BidiLevel and IsRightToLeft values; VisualX still orders script items and the run array remains logical

Resolved runs require valid UTF-16 and reject C0/C1 controls, paragraph/segment separators, U+2028, directional marks, embedding/override/isolate controls and BN characters such as joiners before font acquisition. Validation raises EPdfTextShapingError with a cleared result; the original base-direction modes keep their existing input behavior

Custom backends can call the protected TPdfTextShaper.ValidateResolvedText helper before acquiring a font and must honor the resolved flow and metadata contract. Horizontal bidi paragraph editing forwards already resolved directions during measurement and emission and rejects backends that return inconsistent parity or RTL metadata

These modes shape resolved visible runs and are consumed by the paragraph lanes, which add paragraph-control admission, invisible/control-only spans, cluster-safe word-internal styles and justification; shaping joiners inside a resolved run stay rejected by the resolved-input validator, and vertical shaping and complete Unicode conformance remain outside this unit's contract

Vertical shaping metrics since v3.371.0

ptdTopToBottom requests a top-to-bottom shape. In that mode each glyph's Advance is its vertical advance, positive downward, Width is the total vertical advance of the returned runs, and the run and glyph arrays keep top-to-bottom order. Bidi resolution does not apply to the single vertical column; script segmentation still splits mixed-script text

The HarfBuzz backend reports SupportsVerticalShaping=True and maps HarfBuzz's negative y_advance to that positive advance, with OffsetX as the lateral placement and OffsetY along the column. Vertical forms such as the ideographic comma and full stop come from the font's vertical features, so their glyph identifiers differ from the horizontal shapes

The Uniscribe backend reports False and raises EPdfTextShapingError for a ptdTopToBottom request: the Windows SDK SCRIPT_ANALYSIS structure it drives has no vertical field, so it cannot return vertical metrics. A vertical paragraph layout that consumes these advances remains separate work; this unit only exposes the metrics

Word-context span shaping since v3.367.0

ShapeSpan shapes the complete string and returns only the requested range, rebased so Shaped.Text, the run ranges and every glyph cluster describe the span itself. Both edges must fall on glyph-cluster boundaries; a ligature that crosses either edge raises EPdfTextShapingError instead of being split

The base implementation performs the whole-string shape through the backend's Shape and slices the runs, so Uniscribe and HarfBuzz both keep the contextual forms a cursive-joining script takes from its neighbours. A span that would mix visual run directions is refused, and VisualX is recomputed inside the span

SupportsSpanShaping lets a backend opt out; bidirectional paragraph editing reads it once per execution, admits a word-internal style boundary only when it is True, and otherwise keeps the whole-word rule and reports the refusal through the paragraph report

Selection mapping since v3.365.0

PdfShapedTextSelection accepts a visual glyph range across the returned Runs and returns the minimal logical UTF-16 span that covers those glyphs. A selected glyph always expands to its complete cluster, so a surrogate pair or a many-to-one ligature is never split; ranges that start or end inside a cluster therefore report the whole cluster

Glyph indexes follow the stored run and glyph order, which is visual order, so the mapping also works for right-to-left runs whose clusters descend; an unmapped glyph reports a zero-length span at its recorded cluster position, which the Uniscribe backend now takes from the nearest mapped cluster in visual order, and an empty or out-of-range request clears both outputs and returns False

A saved paragraph line no longer needs reshaping for the same question: since v3.369.0 the line carries a per-glyph cluster table that ReadPdfParagraphClusterMap reads back, and PdfParagraphSelectionFromVisual applies the same cluster-expansion and contiguity rule to that table. The reader validates the table against the saved ActualText and reports unavailable when it does not fit

Example

var
  Shaped: TPdfShapedText;
  MeasuredWidth: Single;
begin
  if ShapePdfText(Text, 'Segoe UI', 12, ptdAuto, Shaped) then
    MeasuredWidth := Shaped.Width;
end;

See Also

TPdf.AddShapedText