Add FPdfParagraphEdit to replace a reviewed contiguous range of text objects with a measured paragraph inside a rectangle in PDF user-space points; the default target selects page objects, while the explicit owned Form target below selects local child objects
PlanStyledPdfParagraph captures reproducible source and prepared snapshots, SHA-256 digests, original text anchors and copied replacement runs; every run refers to one selected source object for its font, size, matrix, exposed colors and painting attributes
ExecuteStyledPdfParagraph checks source identity, preparation identity, origins and text anchors before changing an independent native document; preview returns bytes without replacing the caller, while commit loads only verified output
Page and object indexes are zero-based; SourceObjectIndices must be contiguous text objects, and each run's SourceObjectIndex must belong to that selection
Whitespace separates words, adjacent runs can share a word, repeated spaces and tabs collapse, and CR/LF starts a new line with explicit blank lines retained; a word that cannot fit is rejected rather than split
Alignment selects ppaLeft, ppaCenter, ppaRight or ppaJustify (distributing inter-word space across non-final wrapped lines while keeping the final line of each paragraph left-aligned); FirstLineIndent indents the first line of each paragraph when positive or continuation lines when negative (hanging indent); LineSpacing multiplies the largest selected font height, defaults to 1.2 and accepts 1 through 10
Native glyph measurements include bearings and horizontal advance; source Unicode is qualified before layout, and an explicit standard PostScript FallbackFontName can replace a font that cannot reproduce the requested text
ForceFallbackFont requests the selected fallback directly; fallback is decided for each used style before measuring words, and successful fragments report that decision
The default profile supports upright nonsheared positive scale, opaque fill/stroke and rendering modes 0 through 3; it does not infer script shaping, bidirectional ordering or hyphenation. The explicit Arabic mode below uses a separate bounded path
Selected text must have zero character spacing, word spacing and rise, with 100 percent horizontal text scale; unselected text may not intersect the paragraph rectangle
Existing unselected graphics can remain behind or around the paragraph; replacement fragments occupy the selected range's painter-order slot and the final saved page must match the edited native page pixels
Preparation combines supported local page content streams before replacement; generated object chunks are reassembled in the reviewed order after native saving, so surviving text such as footers does not move before the paragraph
Independent reopen checks page/object correspondence, fragment Unicode, exposed colors, bounds, owned native character order and normalized whole-paragraph text; pixel verification runs at one pixel per PDF point
In the default mode, LogicalText is the normalized text extracted from the final paragraph's actual native characters; Fragments records saved native text, source style indexes, final object/line indexes, bounds, fallback and word-boundary flags. Arabic mode reads logical text from persisted ActualText through its explicit extraction helper
Native extraction can normalize edge spaces; SpaceBefore retains the intended boundary and saved fragment text reflects actual readback
Set EditOptions.ExpandNestedForms consistently at plan and execution time to use the supported untagged Form expansion profile; Origins maps expanded indexes to original instance paths and is checked again during execution
Signed, encrypted and XFA documents, selected clipping/transparency, unsupported content operators and native save layouts that cannot be proven safe reject without publishing partial output
Version 3.208.0 also accepts the complete contiguous group of top-level text objects belonging to one MCID, provided every selected object shares identical native mark identities and stacks and no unselected object shares any of those selected native mark identities
The source follows the simple MCID/Lang/ActualText mark profile of FPdfStyledEdit; structure-ancestor ActualText requires the explicit exclusive-owner option below; separate duplicate MCID sequences, partial group selections and explicit stream MCR bindings on the page remain rejected
With a structure tree, the original MCID must have one leaf page-content binding; generated paragraph fragments are enclosed by one shared marked-content scope after painter-order restoration, without creating MCIDs or changing ParentTree ownership
The saved result verifies identical mark stacks and native group identities across all generated fragments, original page structure-parent keys and retained reachable structure/ParentTree objects, including number-tree children and indirect arrays; page dictionaries are excluded from the graph comparison because their Contents and font resources change
Fragment text, logical reading order, styles, requested bounds and final pixels retain the ordinary verification gates; complete marked groups without a structure tree are also supported, unmarked selected ranges may also retain unrelated tagged structure since v3.290.0
Marked paragraph reflow uses the existing plan, runs, options and report types; tagged Form expansion remains outside this profile
Paragraph execution captures the prepared page's complete serialized declaration frame before native mutation, including objectless BMC/BDC/EMC sequences, empty ordinary MCIDs, MP/DP point marks and resolved named property dictionaries. After replacing the selected interval, it restores every original declaration occurrence with the same name, pairing and order at its mapped native object boundary
Unselected marked objects and Form peers retain their declaration coverage and values. Encoded inline image peers are promoted to image XObjects without rasterization and checked against source declarations and pixels before native content generation. Existing structure and ParentTree objects retain the same ownership, with only the previously supported selected ActualText owner update permitted
SemanticBoundaryPolicy defaults to psbpSourceStyles: each boundary inside the selected interval follows the generated fragments that use earlier source-object styles. This requires nondecreasing source style indexes when an interior declaration exists. Reordered styles or shaped lines with multiple source styles require an explicit policy instead of an inferred semantic location
psbpBeforeReplacement moves all interior boundaries before the replacement; psbpAfterReplacement moves them after it. psbpExplicit requires exactly Length(SourceObjectIndices)-1 nondecreasing SemanticBoundaryOffsets, one per interior source-object boundary, measured as zero-based generated-fragment offsets from the replacement start. Each offset must be between zero and the actual generated-fragment count; other policies require an empty offset array
The plan copies the boundary policy and offset array; execution rejects a changed policy or mapping. SemanticBoundaryMap reports the complete original-to-output boundary map, including the final after-page boundary. Prefix and suffix boundaries retain their order with the appropriate insertion/removal shift. PreservedSemanticMarkCount counts original declaration operations, and PromotedInlineImageCount counts promoted peer images; failure clears these publication fields
Selected complete-group ActualText continues to use the existing innermost canonical owner described below. Other declarations retain their property presence and values, including empty child scopes. Source frames are limited to 64 MiB and 4096 top-level objects; decoded content streams remain limited to 8 MiB each. The full-page frame and native count/type checks must succeed before publication
The original Delphi and FPC Win64 evidence covers 15 positive and eight rejection profiles, with three actual full-save/edit generations for horizontal output and one forward edit/full save for a bidirectional paragraph. Existing Arabic shaping, native vertical same-family fonts and ordinary paragraph controls are checked separately. The later mixed-source, owned Form and saved shaped-source profiles below extend source coverage
MarkPolicy=ppmpCompleteGroup remains the default complete-group behavior. Set MarkPolicy=ppmpMappedSource to reflow a contiguous text selection with different native mark stacks or a selection that covers only part of an existing scope, including scopes shared with unselected page objects
Mapped mode requires an explicit SemanticPolicy: pospPreserveValues retains every original ActualText, Alt and E value, while pospReviewedValues applies the specified SemanticEdits and preserves unlisted values. These are caller decisions; no scope value is inferred from replacement text, no values are consolidated into a new innermost owner, and retained semantic speech can intentionally differ from the new glyph text
SemanticEdits uses the existing TPdfObjectSemanticEdit contract: source-frame declaration indexes identify existing content values and reachable StructElem object numbers identify existing structure values. Only existing ActualText, Alt and E keys can be replaced; empty and supplementary Unicode values are retained without changing property presence. Partial, multi-MCID, ancestor and cross-page owners keep their original bindings; reviewed values may cover unchanged peers and remain the caller's responsibility
The plan independently copies mark/value policies, revision arrays and boundary offsets. Execution rejects changed policies or revisions. Existing SemanticBoundaryPolicy controls every original declaration boundary: monotone source-style provenance is the default, while reordered styles and multi-style shaped lines require an explicit before/after or fragment-offset policy when an interior declaration exists. Scope nesting and declaration occurrence order remain intact even when a mapped scope becomes empty
Mapped BeforeTexts and peer checks use actual glyph text from a private top-level-unmarked snapshot, because native ActualText ownership may move to a different object after the former first object is removed. Original declarations are retained separately and restored only after layout/glyph verification. The final batch validation checks complete declaration coverage, structure/ParentTree ownership, object identity, styles, edited pixels and original foreign pages before publication
Horizontal and native vertical profiles support repeated reflow. Bidirectional and single-style Arabic shaping also retain mapped page declarations, including tagged Arabic source selections; the explicit saved shaped-source profile below enables subsequent reshaping of qualified generated line Forms. The existing script, font, style and shaping limits continue to apply
Mapped mode uses explicit structure revisions instead of AllowAncestorActualText, and requires unexpanded source objects. Signed/encrypted/XFA inputs remain excluded; the owned Form profile below retains existing explicit stream MCR identities after reviewed sharing normalization. Use the existing expansion/verification pixel budgets for the full-document final validation and the remaining scan-work budget for the publication batch
MappedSourceSemantics reports the selected mode and AppliedSemanticValueCount counts explicit revisions. LogicalText continues to report the verified normalized replacement glyph/layout text, independently of preserved or reviewed semantic values. Legacy single-owner report fields remain unused in mapped mode; failure clears semantic publication fields, fragments, maps and output bytes
Delphi/FPC Win64 evidence includes distinct and nested stacks, partial selections, scopes extending outside the selection, named properties, empty/point declarations, cross-page ancestor revisions, preserved/reviewed Unicode and empty values, shared Form and inline image peers, Arabic/bidirectional forward output and three actual horizontal/vertical full-save/reflow generations. Actual object counts remain bounded separately from sparse object-number indexes; the normal reader retains mixed scopes after these saves
Set Target=poetFormInstance, choose a zero-based page FormObjectIndex, and optionally provide FormPath child indexes for a nested Form. SourceObjectIndices and run styles then identify contiguous text children of the selected deepest Form, and Bounds uses that Form's local coordinates before its retained Matrix and ancestor transforms
This profile requires MarkPolicy=ppmpMappedSource, an explicit preserve/review semantic policy, ExpandNestedForms=False and AllowAncestorActualText=False. The selected stream must have one actual page-painted invocation and either internal StructParents ownership or internally owned resource peers. First use reviewed Form normalization for shared internal streams
Planning retains a FormAnchor with original source and private local snapshots, stream number/generation, namespace, selected path and semantic revisions. Execution revalidates those identities before local paragraph work. The selected stream keeps its object identity, BBox, Matrix and namespace; complete original MCR/ParentTree relationships and nonselected owned resource identities survive import and full native saves
postContentMark revisions address the selected Form's original local declaration indexes, postPageContentMark addresses the original page's declaration indexes, and postStructureNode addresses original reachable StructElem object numbers. Existing ActualText, Alt and E values can be retained or explicitly reviewed without moving their ownership; mapped mixed-MCID boundaries follow the existing source-style or explicit boundary policy
Successful reports set FormStructurePreserved, FormStreamObjectNumber, FormStreamGeneration and FormParentTreeKey; the key is -1 for an ordinary container with owned descendants. Fragments and its object indexes describe the local Form children and can select a subsequent unshaped paragraph edit after a full save/reopen. ScanWork includes local paragraph execution and the surrounding Form transaction; failure publishes no bytes or success fields
The qualified horizontal profile includes actual multiline wrapping, mixed MCIDs, named and sparse scopes, nested selection, independent owned peers, ordinary containers, source/ancestor matrices, rotated CropBox geometry, inherited resources, separate Unicode local/page/structure revisions and preview. Verification retains the complete structure graph, all foreign pages and outside-selection pixels, then independently reopens the imported local stream to check its complete declarations and pixels
The saved shaped-source profile below adds explicit glyph-style paths for qualified generated line Forms; general vertical/shaped internal source qualification remains separate work. Whole-object Form StructParent ownership, explicit removal of an owned peer, arbitrary ancestor-value revisions and general appearance/source normalization remain separate requirements. A selected stream reachable through an annotation appearance rejects without output; independent appearances retain their existing support
SourceMode=ppsmTextObjects remains the default. Set SourceMode=ppsmShapedForms to replace a contiguous selection of qualified saved line Forms through horizontal Arabic or bidirectional reshaping. This mode requires mapped semantics, an explicit preserve/review policy and ShapingMode other than ppsNone; it retains the existing supported scripts, font types, boundary policies and shaping restrictions
ReadStyledPdfParagraphFormStyles returns actual source text styles as a TPdfParagraphFormStyles array of TPdfParagraphFormStyle records, with each record's SourceObjectIndex, child FormPath, FontSize and opaque FillColor. It walks bounded nested Forms and restores the caller's selected page. Source Forms must carry readable saved logical ActualText, and their complete native subtree must consist of opaque, unclipped Form/text objects with unit upright transforms and fill-text glyph styles
Since v3.326.0, both ReadStyledPdfParagraphFormStyles and ExtractShapedPdfParagraphText honor Target=poetFormInstance, FormObjectIndex and FormPath. Their input indexes and returned glyph paths then belong to the selected deepest container, matching paragraph planning and execution. A page target requires an empty FormPath; invalid targets and paths reject before returning a different selection
Owned inspection prepares a private snapshot through the same unique-invocation and reciprocal structure checks used by owned paragraph editing, preserves the caller's document and selected page, and subtracts preparation work before reading glyph styles or logical text. It does not apply the caller's pending semantic revisions while reading the source
Each replacement TPdfParagraphRun chooses its selected line through SourceObjectIndex and an actual glyph through SourceFormPath. The plan copies each path independently; execution resolves it again against the immutable prepared snapshot. Replacement runs may reuse different glyph styles within the same line or styles from different selected lines. Logical source anchors come from saved line ActualText, while typography comes from the chosen glyph; native glyph order is not used to reconstruct logical text
Options.SourceMode := ppsmShapedForms; Options.MarkPolicy := ppmpMappedSource; Options.SemanticPolicy := pospPreserveValues; Options.SemanticBoundaryPolicy := psbpBeforeReplacement; Options.ShapingMode := ppsBidirectional; Options.ShapingFontName := 'Arial'; Options.EditOptions.MaxTextScanWork := 256 * 1024 * 1024; Styles := ReadStyledPdfParagraphFormStyles(Pdf, PageIndex, Indices, Options); Runs[0].SourceObjectIndex := Styles[0].SourceObjectIndex; Runs[0].SourceFormPath := Copy(Styles[0].FormPath); Runs[0].Text := 'Updated paragraph text';
With shaped Form sources, optional ShapingStyleFontNames entries correspond to replacement runs, rather than selected line objects; an empty array keeps the common ShapingFontName. Native text mode retains its original per-selected-object font bindings. Nonempty run glyph paths are invalid in native text mode
BeforeTexts retains each selected line's logical source anchor. Fragments.ObjectIndex selects the generated line objects for a later full-save/reopen edit; single-style Arabic fragments and mixed bidirectional ShapedRuns additionally record the original source line and copied SourceFormPath for their style. Several styles can contribute to one bidirectional line, so its fragment may have no single source-object style
Selected line Forms with their own internal structure namespace, whole-object ownership or internally owned resource peers require explicit ownership repair before whole-line replacement. This restriction preserves original MCR/ParentTree relationships; it does not prevent reshaping ordinary generated line children inside an independently preserved owned container. Arbitrary source transforms, vertical shaping, wider Unicode support and exact logical-cluster-to-native-character selection remain separate gates
The recorded Delphi and checked FPC Win64 qualification uses an explicit 256 * 1024 * 1024 scan-work budget for complete embedded-font snapshots and repeated source verification. The default remains 64 * 1024 * 1024; callers select a bounded budget appropriate to their source, and exhausted work or pixel limits preserve the caller without candidate bytes
The separate owned-container combination profile uses 512 * 1024 * 1024 scan-work units for complete document, ownership and local-font verification. It combines three actual reshape/full-native-save/reopen generations with nested selection, second invocations, owned peers, ordinary containers, named source declarations, original matrices and rotated page geometry, and separate supplementary Unicode local/page/structure revisions. This does not change default budgets or qualify general vertical shaping and native character/cluster selection
Version 3.210.0 adds TPdfParagraphWritingMode and WritingMode: ppwHorizontal is the default, while ppwVerticalRightToLeft and ppwVerticalLeftToRight advance downward within columns and select the column progression
Vertical modes reuse actual source vertical fonts such as Identity-V, retaining the native font dictionaries, glyph programs, vertical origins and advances; text matrices remain upright and a horizontal source font is rejected rather than rotated
Source fonts must reproduce the requested Unicode and the measurement sentinel M with a downward vertical advance; standard horizontal fallback fonts are unavailable in vertical mode
Alignment selects column start, center, end or justified spacing; first-line and hanging indentation run downward, line spacing runs across columns, and LineCount/LineIndex describe columns in vertical mode
Common CJK scalar boundaries provide wrap opportunities, with opening/closing punctuation retained beside neighboring text and combining/variation suffixes kept together; this is a bounded profile rather than full Unicode line breaking or shaping
Native object order, per-fragment glyph Unicode, exposed styles, bounds and saved pixels are checked before a complete-column ActualText value establishes the reviewed logical reading order; this avoids native geometric text sorting reversing the requested column order
Unmarked vertical paragraphs receive an unbound Span ActualText scope, while existing MCIDs and leaf bindings remain unchanged; complete unbound simple mark groups are accepted only in untagged documents and can be reflowed again after full saving
Before reproducible pruning, vertical output restores the original font resource names and missing font-object dependencies, preventing the native BaseFont cache from merging horizontal and vertical dictionaries of the same family
Full CJK font programs can require a higher EditOptions.MaxTextScanWork for multi-pass resource and structure verification; the focused full-font evidence uses 256 MiB without changing the default 64 MiB work budget
Since v3.214.0, TPdfParagraphShapingMode selects ppsNone by default or ppsArabicRightToLeft with an explicit ShapingFontName. Planning and execution keep the same snapshot, preview and commit contract
The Arabic profile requires one run and one unmarked fill-text source style, unit upright scale, an untagged document and horizontal writing. It accepts Arabic letters from the main, Supplement and Extended-A blocks, Quranic and Extended-A combining marks, ASCII and Arabic-Indic digits, selected Arabic punctuation and whitespace, with left, center, right or justify alignment and first-line or hanging indentation; justify stretches inter-word spaces on every line except the last of its paragraph since v3.366.4, and since v3.366.11 a line that ends at an explicit break or is followed by another paragraph keeps its natural spacing; digits stay in their right-to-left run, while Latin text, other scripts, explicit bidi controls, marked sources, expanded Forms and mixed styles are rejected
The active shaping backend supplies explicit glyph IDs, offsets, advances and clusters. Wrapping occurs only between whitespace-delimited words, preserving ligatures and combining clusters within each word; oversized words are rejected. Final line glyph bounds determine line height, and LineSpacing adds a font-size-based gap between lines
Each line receives an independent Form XObject and CID font mapping, preventing native BaseFont resource reuse from collapsing different line maps. Fragments now identify Form objects in this mode, with one nonempty line per fragment; blank lines contribute to LineCount without adding a Form
Call ExtractShapedPdfParagraphText with the zero-based page index and increasing Form object indexes from Fragments to read normalized logical text from the saved UTF-16BE ActualText values. The helper follows bounded Form/text nodes, requires explicit unique ActualText ownership and rejects other drawing objects or malformed text
NativeShapingTextOrderMatches separately reports whether the native character API returns the same logical order. The recorded ordinary Win64 DLL reverses characters within some Arabic words, so all eleven positive native profiles report False while persisted ActualText and the explicit logical extraction helper remain correct; raw PDFium character order is not repaired or silently reinterpreted
Static standalone TrueType font bytes must satisfy the existing embedding/subsetting permission checks; each font is limited to 16 MiB, each measured line to 4096 UTF-16 units and 65534 glyphs, also subject to the caller's smaller character/run/fragment budgets. Font bytes must remain identical throughout layout. These accepted-data limits do not bound every native allocation
Focused Delphi Win64 acceptance covers Arabic ligatures, vowel marks, wrapped and blank lines, alignment/indentation, preview, rejection without caller mutation, optional-shaper failures and two full-save/reopen generations. Independent HarfBuzz/fontTools checks compare the embedded glyph sets and pypdf reads persisted logical text; other scripts, compiler/platform pairs, tagged output and general Unicode line breaking remain outside this profile
Set ShapingMode=ppsBidirectional for horizontal Unicode scalar paragraphs supplied by explicit static fonts, with multiple selected source styles, including untagged paragraphs and the existing complete page-MCID group profile; style boundaries fall between complete words for cursive-joining scripts and may fall on a cluster boundary inside any other word since v3.366.6, while since v3.367.0 a backend that keeps span context (SupportsSpanShaping) shapes each span with the complete word and admits the same cluster boundary inside a cursive-joining word Source font sizes and opaque fill colors are retained; explicit static TrueType shaping fonts replace the original font programs
Since v3.373.0 AllowShapingJoiners admits ZWNJ (U+200C) and ZWJ (U+200D) through the bidirectional lane: the joiner stays in the rendered shaping text with its original logical offset, so the backend applies the breaking or joining effect the text requests. A backend that returns no glyph for ZWJ has that unit folded into a neighboring saved cluster, including a following cluster for a leading joiner, and boundaries immediately next to ZWJ are accepted in this lane, so the saved table still tiles the line. The default False keeps rejecting them exactly as the released profile does; other boundary neutrals remain unsupported
ShapingStyleFontNames is either empty or aligned with SourceObjectIndices. An empty array uses ShapingFontName for every style; an empty array entry uses that same global name. Each effective font name must be explicit and bounded. Different styles must meet between complete whitespace-delimited words, preserving Arabic joining and combining context within each word; since v3.366.6 a style boundary may also fall inside a word that carries no cursive-joining script, provided it lands on a grapheme-cluster boundary, so a Latin, Greek, Cyrillic or Hebrew word can mix styles per cluster run while Arabic, Syriac, N'Ko, Mongolian, Manichaean and Psalter Pahlavi words keep the whole-word rule
Since v3.366.10 ppaJustify stretches the gaps between words on every line except the last of a paragraph, in both paragraph directions; a justified line keeps each word in its own shaped segment so joining and clustering stay per word, a single word with no gap stays natural, and the final line keeps its natural spacing
Each explicit paragraph chooses its base direction from its first strong character and retains that direction across wrapping. Since v3.338.0, complete paragraph levels are resolved once before measuring candidate lines; copied per-line levels receive the L1 reset after their boundaries are known, preserving bracket, neutral and number context across wrapping. The resulting line levels determine visual style runs before shaping each run; left, center and right alignment and first-line/hanging indentation are available. Indentation excludes the leading side of the paragraph, which is the right side for RTL paragraphs
Each visual style run uses an independent CID font scope. One inner Form mark per nonempty line stores its complete logical UTF-16BE ActualText with PdfParagraphLine=1; generated glyph marks are removed to avoid duplicate semantic ownership. The existing page MCID group wraps all output line Forms once, and declared content, leaf or exclusive ancestor ActualText receives the complete verified logical paragraph
Fragments identifies saved line Forms; SourceObjectIndex=-1 means a line can contain several styles. ShapedRuns reports each visual run with its source style object index, zero-based line and UTF-16 logical range, resolved bidi level, glyph count, requested font name, size, fill color, advance and page bounds. Failure clears both arrays; a visual glyph range of the shaped record maps to logical text with PdfShapedTextSelection, while the saved runs expose run-level logical ranges and, since v3.369.0, a per-glyph cluster map
Use ExtractShapedPdfParagraphText for persisted normalized logical text. NativeShapingTextOrderMatches separately compares native glyph text owned by the paragraph, excluding unrelated page text; it can be False even when saved logical semantics and glyph placement are correct. Logical replacement text does not establish an exact native character-selection mapping
Since v3.339.0, measurement and emission forward each resolved run parity through ptdResolvedLeftToRight or ptdResolvedRightToLeft. Custom shapers must retain that flow and return consistent bidi parity and IsRightToLeft; inconsistent metadata rejects the transaction without publishing output
Version 3.337.0 admits valid Unicode scalars beyond the earlier Latin/Arabic/Hebrew ranges, including supplementary-plane characters and presentation forms, when the explicit permitted static TrueType font and shaping backend supply every glyph. Run- or word-initial nonspacing marks and unsupported boundary neutrals remain rejected
Run and cluster offsets are zero-based UTF-16 code-unit ranges. Paragraph validation rejects ranges that split a surrogate pair, overlapping text runs, incomplete logical run/cluster coverage and inconsistent logical counts; coverage work consumes the existing scan-work budget. Font glyph availability and finite geometry checks still apply
Hebrew shares the same automatic paragraph-direction resolution, cluster-safe style boundaries (including inside a word), logical line ActualText ownership, supported page-MCID/leaf/exclusive-ancestor preservation and two dirty-save checks
Joiners and other unsupported boundary neutrals, unsupported paragraph separators, run- or word-initial nonspacing marks, style changes inside a cursive-joining word, vertical shaping, expanded source Forms and non-fill or non-unit upright source styles remain outside this horizontal profile. Missing glyphs and malformed UTF-16 reject without publishing partial output. Static font embedding permissions and the existing finite line/font/scan/pixel budgets still apply; broader Unicode conformance and exact native character/cluster selection remain separate requirements
RenderVerticalParagraph lays a paragraph down upright vertical columns that progress right to left from X, breaking between clusters when the next glyph would leave ColumnHeight; each paragraph and each explicit line break starts a new column, and the shaping backend must report vertical metrics
TPdfVerticalParagraphOptions.Default sets MaxColumns 256, MaxCharacters 65536, black Color and opaque Alpha; ColumnGap adds space between columns, ColumnsPerPage with PageWidth and PageHeight continues the columns that do not fit on new pages, Justify spreads a short column to the column height except for the last column of a paragraph, Balance gives a multi-column paragraph an equal glyph count per column, and CancellationToken cancels the call, which then reports Cancelled
TPdfVerticalParagraphReport returns Succeeded, Cancelled and Overflow (the paragraph needs more than MaxColumns and nothing is written) with the Columns, Glyphs, Breaks, Justified, Pages and BalancedParagraphs counts, the laid-out Width and Height and an ErrorMessage
TPdfVerticalParagraphReport.Slices keeps the shaped record of every emitted column in page coordinates, so a caller can hit-test a vertical paragraph and fold the glyph indices through PdfShapedTextSelection instead of losing the mapping to the column layout; TPdfVerticalParagraphReport.ColumnObjects names the first page object of each column in the same order; from internal version 3.396.3 its shared column scope persists through native saves and participates in batch invalidation
Bidirectional and Arabic lines, and vertical columns (from internal version 3.396.3) carry one private PdfParagraphClusterMap blob in saved glyph order. From internal version 3.396.2 new maps use bytes 50 43 4D 02, a 16-bit little-endian glyph count, two zero reserved bytes, a 32-bit logical UTF-16 length and 32 SHA-256 bytes over the logical UTF-16BE units without a BOM; 12-byte little-endian triples follow at offset 44 (glyph index, logical start, logical length). Existing version-1 tables use the same triples at offset 8 and remain readable when their ranges cover their logical owner
ReadPdfParagraphClusterMap(Pdf, LineFormIndex, out Entries) searches a selected line Form for exactly one table and checks its nearest unambiguous ActualText owner. It checks UTF-16 scalar boundaries, integer ranges and complete logical coverage, and verifies the length and digest for version 2. A changed same-length ActualText owner therefore invalidates a new table; version 1 has no text-identity binding. Missing, ambiguous or malformed mappings report False and clear the output array
Since internal v3.397.0, ReadPdfParagraphClusterMap(Pdf, PageObjectIndex, FormPath, out Entries) selects one line Form inside a nested or owned container. The root index and every path component are zero-based native object indices on the current page; at most 32 child indices are accepted, every intermediate object must be a Form, and the final object must be a line Form with one unambiguous table. The overload does not change the document, current page or supplied path; an empty path is equivalent to the original top-level reader
For an owned paragraph, concatenate Options.FormPath with Report.Fragments[I].ObjectIndex and use Options.FormObjectIndex as the root on the paragraph's page. Maps survive the recorded owned stream replacement and dirty-save profile; deleting a different line preserves the remaining map, with its new local index obtained from the edit report. Paths identify the current native graph, so refresh them after edits that change object membership. An entire multi-line container is ambiguous and reports False
Each TPdfParagraphClusterEntry holds GlyphIndex, LogicalStart and LogicalLength. PdfParagraphSelectionFromVisual unions identical spans when several glyphs share one cluster, accepts only a contiguous interval of distinct clusters, and rejects partial overlaps, gaps and integer overflow. The table is bounded to 65534 glyphs and the paragraph byte budget
Batch object edits preserve this reserved parameter in the semantic frame and remove it from declaration scopes affected by text replacement, removal, insertion or an overlapping reviewed ActualText revision. Property-only edits and unaffected sibling declarations retain their maps. These rules do not establish glyph identity after arbitrary external stream changes, and the digest is a staleness check rather than an authenticity guarantee. Nested vertical sibling lookup follows in internal v3.398.0; internal v3.400.0 adds optional native character association for validated line and PCM2 column scopes, while arbitrary source-Form glyph authenticity remains outside the metadata checks and bundled Windows native delivery follows in internal version 3.401.0
From internal version 3.396.3 each newly emitted vertical column has one shared Span with its complete ActualText and PCM2 table, spanning all consecutive glyph objects; the emitter regenerates native content after attaching that scope. ReadPdfVerticalClusterMap requires the first object named by ColumnObjects and checks that exactly the table's glyph count of consecutive text objects share that single mark. An interior object, missing member, extra member or changed ActualText reports False; text, insertion, removal and reviewed ActualText edits inside the shared declaration invalidate the entire column table, while color/property edits and unchanged columns retain theirs
Since internal v3.398.0, ReadPdfVerticalClusterMap(Pdf, PageObjectIndex, FormPath, out Entries) resolves the column's first glyph inside a nested Form. The last path component is the first glyph's index in its containing Form; membership is checked against that Form's complete sibling collection, independently for the selected invocation. The path has the same 32-child limit and current-page, zero-based convention as the horizontal overload. Empty paths keep the original page-level behavior, including legacy PCM1 bounds-only compatibility; nonempty paths must end on a text object, and interior members or malformed scopes report False
ReadPdfParagraphNativeMap and ReadPdfVerticalNativeMap join these tables to exact native character indices through the optional provenance extension, included in all four bundled Windows DLL profiles since internal v3.401.0; other builds without it return unavailable. Results distinguish physical glyph ordinals from ActualText declaration offsets, retain independent invocation ownership, omit generated characters and report unmatched declarations. PdfParagraphSelectionFromNative accepts only fully mapped native ranges and returns complete contiguous logical clusters; see native map fields, bounds and lifetime. A returned TPdfParagraphNativeMap carries the source Clusters, one TPdfParagraphNativeCharacter per mapped character in the Characters array, the UnmappedCharacterCount of native characters that no declaration covers, and the stored FormatVersion; each character entry records its own indices, its ActualTextOffset, and a Kind of pnckGlyph for a physical glyph or pnckActualText for a declaration-supplied character
Internal v3.403.0 extends table invalidation to direct text, object and ActualText edits and retains mappings after geometry/style updates across represented shared scopes in adjacent content streams. Extra metadata-only marks are accepted only with exact column owner/table membership and no owner reuse elsewhere in the containing collection. Named-property detachment preserves independent declarations and nested values; see the native map contract and remaining source-preservation boundaries
The legacy PCM1 visual-table reader retains structural and integer-range compatibility. Internal v3.402.0 adds native association for the original per-glyph ActualText writer profile, including local declaration offsets, contiguous logical coverage and distinct owner/membership checks; TPdfParagraphNativeMap.FormatVersion distinguishes PCM1 from PCM2. Supported batch member and ActualText edits invalidate the old table across its declared column, while property-only edits and unaffected columns retain it. PCM1 has no whole-column text digest or shared-ownership certificate; arbitrary external glyph-stream changes and source-Form authenticity remain separate requirements. TPdfVerticalParagraphReport.Slices continues to support in-memory hit testing
ppsBidirectional retains all twelve Unicode Bidi_Control characters in the original paragraph, saved line ActualText and ShapedRuns.Text. Embeddings, overrides, isolates and directional marks therefore keep their original cross-line and logical UTF-16 context
Glyph input is a separate string produced by PdfBidiRenderText; its map identifies original logical units without changing the public report record layout. Pass the run text and LogicalStart to reconstruct this mapping. Formatting controls never become visible glyphs or consume advance width
A control-only run reports GlyphCount=0, zero advance and degenerate page bounds, while retaining its logical range and declared source size/color. It does not call the shaping backend. The saved line retains a nonstroked zero-area opaque path carrying validated invisible-span typography, so a line with no glyphs can survive native saves and supply a style for a later ppsmShapedForms edit
Saved carrier admission requires finite zero-area line geometry, the supported binary typography payload, one matching line owner, a valid control-only logical span and the existing upright opaque unclipped source transforms. Painted or stroked paths, duplicate owners/markers and malformed sizes, colors or spans reject. Arbitrary drawings do not become source text styles
Control-containing paragraph resolution reserves conservative quadratic scan work before the bidi core runs; existing caller budgets and cancellation remain authoritative. The finite horizontal profile retains cluster-safe style boundaries, whole-word for cursive-joining scripts, and explicit static fonts. Saved-source edits require the existing explicit semantic policy: pospPreserveValues keeps original declaration/structure values, while pospReviewedValues applies the caller's reviewed revisions
Delphi and FPC Win64 acceptance checks two dirty native save generations, line semantics, original structure/ParentTree relationships and rejection preservation. Independent pypdf/fontTools/HarfBuzz inspection checks embedded glyph identity, saved glyph positions and colors; whole-line Uniscribe supplies a separate visual-order reference. Its level-2 Latin-context digits are equivalent to UAX #9 W7 level 0 and are recorded separately; finite point tolerances account for pixel-quantized Uniscribe versus unhinted HarfBuzz metrics
AllowAncestorActualText defaults to False. Set it explicitly for complete marked paragraph replacement when exactly one existing ancestor ActualText owner covers only the selected leaf: every node from that ancestor to the leaf must have exactly one child and no direct content items, and the leaf must retain its single page/MCID binding
The option accepts empty or nonempty owner values, intermediate single-child containers, direct/Kids/indirect-Nums ParentTrees and coextensive content ActualText. A separate unrelated branch above the owner remains unchanged. A leaf ActualText plus an ancestor, a second ancestor owner, a sibling under the owner or direct content in its branch remains rejected
Before editing, bounded inspection verifies the page StructParents key has one content owner and the ParentTree contains the matching leaf reference exactly once at that key's MCID slot. Keys must be ordered and unique; child Limits must match the traversed ranges. Duplicate slots, wrong mappings, missing slots, cycles and invalid limits reject before publication
The owner receives verified LogicalText after native glyph/style/reading-order checks; other structure and ParentTree objects stay byte-identical in the helper output. The owner's non-ActualText metadata and child identities are checked separately, allowing only equivalent one-item K array serialization. Saved output is reparsed, re-rendered and checked again for the same semantic owner and binding
On success, ActualTextOwnerNodeID names the existing updated structure owner; UpdatedAncestorActualText is True when that owner is an ancestor rather than the leaf. Failure resets both fields and publishes no output. Preview returns the verified PDF without changing the caller; commit uses the existing atomic replacement contract
The original ancestor profile covers top-level complete paragraph groups on the recorded Delphi Win64 runtime. The separate mixed bidirectional profile above also retains this declared ownership model; tagged Form expansion, partial semantic edits, arbitrary ancestor branches and general ParentTree repair remain excluded
Version 3.209.0 also accepts existing content and leaf ActualText, including empty values and coextensive nested content scopes, when the complete marked group is selected
Existing content ActualText is consolidated into one value on the innermost mark and replaced with the verified normalized LogicalText; all tag names, MCIDs and language values remain unchanged, and no content ActualText is introduced when none existed
This canonical placement avoids the current native extractor dropping outer ActualText when an inner property dictionary lacks it; complete-group ownership makes the replacement scope explicit
An existing leaf ActualText is updated to the same LogicalText after glyph-level verification; absent leaf ActualText remains absent, structure ancestors remain unchanged under the default policy, and a single K binding may normalize to a one-element array with the same page/MCID identity
Fragment text, styles and reading order are verified before semantic substitution, so Fragments.Text records the actual glyph text rather than the group's repeated ActualText; final native semantic extraction, mark ownership, structure bindings and pixels are checked again after substitution
Reachable structure and ParentTree objects remain byte-identical except for the reviewed semantic owner ActualText update and equivalent K serialization; all other leaf metadata is compared independently of dictionary whitespace
Start with TPdfParagraphOptions.Default; inherited edit limits govern source bytes, page/object/character counts, cancellation and scan work, with paragraph defaults of 128 MiB and 1,048,576 UTF-16 units
MaxRuns defaults to 4,096 with hard maximum 100,000; MaxLines defaults to 10,000 with hard maximum 100,000; MaxFragments and MaxMeasurements default to 100,000 with hard maximum 1,000,000
MaxVerificationPixels independently bounds final paragraph-page verification at 16,777,216 pixels by default, with hard maximum 268,435,456; Form preparation uses the separate inherited MaxExpansionPixels phase budget
Bounds must be finite, nonempty, inside the page MediaBox and within plus or minus 32,768 points; line or height overflow fails without partial output
TPdfParagraphReport records success, cancellation, preview mode, line/generated/fallback/measurement counts, source/output hashes, error text, logical text and fragments; failure clears output bytes and publication counts while retaining diagnostic measurement work
See FPdfStyledEdit for literal/regex replacement and reviewed unique/shared-MCID object editing
uses SysUtils, Classes, PDFium, FPdfStyledEdit;
type
TPdfParagraphAlignment=(ppaLeft,ppaCenter,ppaRight,ppaJustify);
TPdfParagraphWritingMode=(ppwHorizontal,ppwVerticalRightToLeft,ppwVerticalLeftToRight);
TPdfParagraphShapingMode=(ppsNone,ppsArabicRightToLeft,ppsBidirectional);
TPdfParagraphMarkPolicy=(ppmpCompleteGroup,ppmpMappedSource);
TPdfParagraphSemanticBoundaryPolicy=(psbpSourceStyles,psbpBeforeReplacement,psbpAfterReplacement,psbpExplicit);
TPdfParagraphSourceMode=(ppsmTextObjects,ppsmShapedForms);
TPdfParagraphObjectIndices=array of Integer;
TPdfParagraphTexts=array of WideString;
TPdfParagraphRun=record
SourceObjectIndex:Integer;
Text:WideString;
end;
TPdfParagraphRuns=array of TPdfParagraphRun;
TPdfParagraphOptions=record
EditOptions:TPdfStyledEditOptions;
Alignment:TPdfParagraphAlignment;
WritingMode:TPdfParagraphWritingMode;
ShapingMode:TPdfParagraphShapingMode;
ShapingFontName:WideString;
ShapingStyleFontNames:TPdfParagraphTexts;
AllowAncestorActualText:Boolean;
AllowShapingJoiners:Boolean;
MarkPolicy:TPdfParagraphMarkPolicy;
SemanticPolicy:TPdfObjectSemanticPolicy;
SemanticEdits:TPdfObjectSemanticEdits;
SemanticBoundaryPolicy:TPdfParagraphSemanticBoundaryPolicy;
SemanticBoundaryOffsets:TPdfParagraphObjectIndices;
LineSpacing,FirstLineIndent:Double;
MaxVerificationPixels:Int64;
MaxRuns,MaxLines,MaxFragments,MaxMeasurements:Integer;
class function Default:TPdfParagraphOptions; static;
end;
TPdfParagraphPlan=record
SourceBytes,PreparedBytes:TBytes;
SourceSha256,PreparedSha256:string;
ExpandedNestedForms:Boolean;
Origins:TPdfStyledObjectOrigins;
PageIndex:Integer;
SourceObjectIndices:TPdfParagraphObjectIndices;
BeforeTexts:TPdfParagraphTexts;
Runs:TPdfParagraphRuns;
Bounds:TPdfRectangle;
MarkPolicy:TPdfParagraphMarkPolicy;
SemanticPolicy:TPdfObjectSemanticPolicy;
SemanticEdits:TPdfObjectSemanticEdits;
SemanticBoundaryPolicy:TPdfParagraphSemanticBoundaryPolicy;
SemanticBoundaryOffsets:TPdfParagraphObjectIndices;
end;
TPdfParagraphFragment=record
SourceObjectIndex,ObjectIndex,LineIndex:Integer;
Text:WideString;
Bounds:TPdfRectangle;
FontFallback,SpaceBefore:Boolean;
end;
TPdfParagraphFragments=array of TPdfParagraphFragment;
TPdfParagraphShapedRun=record
SourceObjectIndex,LineIndex,LogicalStart,LogicalLength,BidiLevel,GlyphCount:Integer;
Text,FontName:WideString;
FontSize:Single;
FillColor:Integer;
Advance:Double;
Bounds:TPdfRectangle;
end;
TPdfParagraphShapedRuns=array of TPdfParagraphShapedRun;
TPdfParagraphReport=record
Succeeded,Cancelled,PreviewOnly:Boolean;
NativeShapingTextOrderMatches:Boolean;
MappedSourceSemantics:Boolean;
AppliedSemanticValueCount:Integer;
UpdatedAncestorActualText:Boolean;
ActualTextOwnerNodeID:Integer;
PreservedSemanticMarkCount,PromotedInlineImageCount:Integer;
SemanticBoundaryMap:TPdfParagraphObjectIndices;
LineCount,GeneratedObjectCount,FontFallbackCount,MeasurementCount:Integer;
SourceSha256,OutputSha256,ErrorMessage:string;
LogicalText:WideString;
Fragments:TPdfParagraphFragments;
ShapedRuns:TPdfParagraphShapedRuns;
end;
function PlanStyledPdfParagraph(Pdf:TPdf; PageIndex:Integer;
const SourceObjectIndices:TPdfParagraphObjectIndices; const Runs:TPdfParagraphRuns;
const Bounds:TPdfRectangle; const Options:TPdfParagraphOptions):TPdfParagraphPlan;
function ExecuteStyledPdfParagraph(Pdf:TPdf; const Plan:TPdfParagraphPlan;
const Options:TPdfParagraphOptions; out PreviewPdf:TBytes;
out Report:TPdfParagraphReport):Boolean;
function ExtractShapedPdfParagraphText(Pdf:TPdf; PageIndex:Integer;
const FormObjectIndices:TPdfParagraphObjectIndices;
const Options:TPdfParagraphOptions):WideString;
function ReadStyledPdfParagraphFormStyles(Pdf:TPdf;PageIndex:Integer;
const FormObjectIndices:TPdfParagraphObjectIndices;
const Options:TPdfParagraphOptions):TPdfParagraphFormStyles;
type
TPdfParagraphClusterEntry=record
GlyphIndex,LogicalStart,LogicalLength:Integer;
end;
TPdfParagraphClusterEntries=array of TPdfParagraphClusterEntry;
TPdfParagraphNativeCharacterKind=(pnckGlyph,pnckActualText);
TPdfParagraphNativeCharacter=record
CharacterIndex,GlyphIndex,LogicalStart,LogicalLength,ActualTextOffset:Integer;
Kind:TPdfParagraphNativeCharacterKind;
end;
TPdfParagraphNativeCharacters=array of TPdfParagraphNativeCharacter;
TPdfParagraphNativeMap=record
Clusters:TPdfParagraphClusterEntries;
Characters:TPdfParagraphNativeCharacters;
UnmappedCharacterCount:Integer;
FormatVersion:Integer;
end;
TPdfVerticalParagraphOptions=record
MaxColumns,MaxCharacters:Integer;
ColumnGap:Double;
ColumnsPerPage:Integer;
PageWidth,PageHeight:Double;
Justify:Boolean;
Balance:Boolean;
Color:TColor;
Alpha:Byte;
CancellationToken:IPdfCancellationToken;
class function Default:TPdfVerticalParagraphOptions; static;
end;
TPdfVerticalParagraphReport=record
Succeeded,Cancelled,Overflow:Boolean;
Columns,Glyphs,Breaks,Justified,Pages,BalancedParagraphs:Integer;
Width,Height:Double;
ErrorMessage:string;
Slices:array of TPdfShapedText;
ColumnObjects:array of Integer;
end;
function ReadPdfParagraphClusterMap(Pdf:TPdf; LineFormIndex:Integer;
out Entries:TPdfParagraphClusterEntries):Boolean; overload;
function ReadPdfParagraphClusterMap(Pdf:TPdf; PageObjectIndex:Integer;
const FormPath:TPdfStyledFormPath;
out Entries:TPdfParagraphClusterEntries):Boolean; overload;
function ReadPdfVerticalClusterMap(Pdf:TPdf; PageObjectIndex:Integer;
out Entries:TPdfParagraphClusterEntries):Boolean; overload;
function ReadPdfVerticalClusterMap(Pdf:TPdf; PageObjectIndex:Integer;
const FormPath:TPdfStyledFormPath;
out Entries:TPdfParagraphClusterEntries):Boolean; overload;
function PdfParagraphSelectionFromVisual(const Entries:TPdfParagraphClusterEntries;
FirstGlyph,GlyphCount:Integer; out LogicalStart,LogicalLength:Integer):Boolean;
function ReadPdfParagraphNativeMap(Pdf:TPdf;PageObjectIndex:Integer;
const FormPath:TPdfStyledFormPath;out Map:TPdfParagraphNativeMap):Boolean;
function ReadPdfVerticalNativeMap(Pdf:TPdf;PageObjectIndex:Integer;
const FormPath:TPdfStyledFormPath;out Map:TPdfParagraphNativeMap):Boolean;
function PdfParagraphSelectionFromNative(const Map:TPdfParagraphNativeMap;
FirstCharacter,CharacterCount:Integer;out LogicalStart,LogicalLength:Integer):Boolean;
function RenderVerticalParagraph(Pdf:TPdf; const Text, Font:WString;
FontSize:Single; X, Y, ColumnWidth, ColumnHeight:Double;
const Options:TPdfVerticalParagraphOptions;
out Report:TPdfVerticalParagraphReport):Boolean;