/** * Pagination engine for creating a PDF.js-style paginated view from HTML output. * * This module provides client-side pagination that measures rendered content * and flows it across fixed-size page containers based on document dimensions. */ import type { PageDimensions } from "./page-geometry.js"; import { type MarkupBalloonResult, type MarkupMode } from "./markup-balloons.js"; export type { PageBands, PageDimensions } from "./page-geometry.js"; /** * Headers and footers for a specific section. */ export interface SectionHeaderFooter { /** Default header (used for odd pages or all pages) */ headerDefault?: HTMLElement; /** First page header */ headerFirst?: HTMLElement; /** Even page header */ headerEven?: HTMLElement; /** Default footer (used for odd pages or all pages) */ footerDefault?: HTMLElement; /** First page footer */ footerFirst?: HTMLElement; /** Even page footer */ footerEven?: HTMLElement; /** Measured height of default header in points */ headerDefaultHeight?: number; /** Measured height of first page header in points */ headerFirstHeight?: number; /** Measured height of even page header in points */ headerEvenHeight?: number; /** Measured height of default footer in points */ footerDefaultHeight?: number; /** Measured height of first page footer in points */ footerFirstHeight?: number; /** Measured height of even page footer in points */ footerEvenHeight?: number; } /** * Registry of headers and footers by section index. */ export type HeaderFooterRegistry = Map; /** * A measured content block with metadata for pagination decisions. */ export interface MeasuredBlock { /** The DOM element */ element: HTMLElement; /** Section whose body owns this block after a continuous section transition. */ sectionIndex: number; /** Measured height in points (content + padding + border, excluding margins) */ heightPt: number; /** * Extra leading in points that an auto line-spacing multiple adds below the last line's text. * Word lets it run past the bottom margin (issue #1571), so the block fits by `heightPt` less this. */ trailingLeadingPt?: number; /** Inline frame paint's furthest bottom from this block's top, independent of its flow height. */ frameExtentPt?: number; /** Extra source-flow gap imposed by preceding floats, after ordinary margin collapse. */ clearancePt?: number; /** Top margin in points */ marginTopPt: number; /** Bottom margin in points */ marginBottomPt: number; /** Whether to keep this block with the next one */ keepWithNext: boolean; /** Whether to keep all lines of this block together */ keepLines: boolean; /** A fresh-page attempt could not honor this paragraph's keep-lines constraint. */ relaxedKeepLines?: boolean; /** An oversized body paragraph could not honor keep-with-next on a fresh page. */ relaxedKeepWithNext?: boolean; /** Whether to force a page break before this block */ pageBreakBefore: boolean; /** Whether this is a page break marker */ isPageBreak: boolean; /** Whether the block's top margin is Word paragraph space-before; see `hasParagraphSpacing` */ isWordParagraph?: boolean; } /** * Information about a rendered page. */ export interface PageInfo { /** 1-based page number */ pageNumber: number; /** Section index this page belongs to */ sectionIndex: number; /** Page dimensions */ dimensions: PageDimensions; /** The page container element */ element: HTMLElement; } /** The balloon layout's result, with the pages its appendix added after the last (if any). */ export type MarkupBalloonLayout = MarkupBalloonResult & { appendedPages: PageInfo[]; }; /** * Result of pagination operation. */ export interface PaginationResult { /** Total number of pages */ totalPages: number; /** Array of page information */ pages: PageInfo[]; /** Present only when the caller supplied an exact layoutToken. */ pageMap?: PageMap; } export type PageMapMode = "paginated" | "continuous"; export type PageMapAvailability = "available" | "unavailable"; export type PageMapStory = "body" | "header" | "footer" | "footnote" | "endnote" | "comment"; export interface PageMapRect { /** Page-relative points, independent of viewer zoom/transform. */ x: number; y: number; width: number; height: number; } export interface PageMapPage { pageNumber: number; pageInSection: number; width: number; height: number; sectionIndex?: number; pageName: string; } export interface PageMapFragment { fragmentId: string; /** Canonical collision-safe `kind:scope:unid`, never the bare editor Unid. */ anchorId: string; fragmentIndex: number; pageNumber: number; geometry: PageMapRect; story: PageMapStory; /** Table-cell ownership is orthogonal to story (e.g. a body or footnote table cell). */ inTableCell: boolean; } /** Versioned portable layout contract consumed by DocxSession and remote agent surfaces. */ export interface PageMap { schemaVersion: 1; mode: PageMapMode; availability: PageMapAvailability; documentVersion: number; rendererFingerprint: string; pages: PageMapPage[]; fragments: PageMapFragment[]; } /** Explicit no-pages contract for a continuous viewer. It never estimates page numbers. */ export declare function createUnavailablePageMap(documentVersion: number, rendererFingerprint: string, mode?: "continuous"): PageMap; export interface PageCitationNavigation { navigated: boolean; target?: HTMLElement; pageNumber?: number; fragmentId?: string; unavailableReason?: "citation_unavailable" | "fragment_not_found"; } /** Remove the citation highlight previously applied within this paginated root. */ export declare function clearPageCitationHighlight(root: ParentNode): void; /** * Navigate an exact citation over an already-paginated DOM. The page-qualified fragment id is * authoritative; page + canonical source identity is a compatibility fallback for older v1 DOMs. */ export declare function navigateToPageCitation(root: ParentNode, citation: { availability: PageMapAvailability; anchorId: string; fragments: Array<{ fragmentId: string; pageNumber: number; }>; }, options?: { highlightClass?: string; /** Apply a visible inline highlight when no class is supplied. Default true. */ highlight?: boolean; behavior?: ScrollBehavior; block?: ScrollLogicalPosition; }): PageCitationNavigation; /** * Options for the pagination engine. */ export interface PaginationOptions { /** Scale factor for rendering (1.0 = 100%). Default: 1 */ scale?: number; /** CSS class prefix used in the HTML. Default: "page-" */ cssPrefix?: string; /** Whether to show page numbers. Default: true */ showPageNumbers?: boolean; /** Gap between pages in pixels. Default: 20 */ pageGap?: number; /** * Comment placement: physical margin for PaginationEngine, outside for paginateHtml, or * "balloons" for Word's All Markup print (issue #1300, markup-balloons.ts): pages shrink beside * a markup area holding comments and, with Word-presentation HTML, formatting changes. As with * "outside", comments then have no PageMap citations. */ commentColumnPlacement?: "margin" | "outside" | "balloons"; /** Physical-margin overflow: scroll in viewers (default), or append complete threads for print. */ commentOverflow?: "scroll" | "appendix"; /** * Under "balloons", what becomes of the rest of a comment whose balloon is cut short to fit beside * its page. "truncate" (the default) prints it nowhere, as Word's Save as PDF does. "appendix" * numbers each cut comment's box and prints the comments in full on pages added after the last, * as Word's Print to PDF does; those pages join the result and the PageMap. */ balloonOverflow?: "truncate" | "appendix"; /** * Under "balloons", Word's balloon setting that decides what they hold. "mixed" (the default) is * Word's own default, "Show Only Comments and Formatting in Balloons". "inline" is "Show All * Revisions Inline": comments only, so a document whose only markup is formatting changes prints * at full size, the changes keeping their change bars. */ markupMode?: MarkupMode; /** Outside comment-column width in points. Default: 144 (2 inches). */ commentColumnWidthPt?: number; /** Gap between the page and an outside comment column, in points. Default: 12. */ commentColumnGapPt?: number; /** * Whether ordinary paragraphs may be fragmented across page boundaries. * Defaults to false for direct PaginationEngine callers; read-only viewer * entry points opt in explicitly. */ fragmentParagraphs?: boolean; /** * Put each line's glyphs on Word's baseline once the pages are laid out (issue #942), moving * them with relative positioning so no line box changes. Defaults to false for direct * PaginationEngine callers; the read-only viewer entry points opt in. An editable surface * keeps it off (typed text would land in unmoved boxes), and the standalone export runs the * same pass itself after its clipping check. */ alignBaselinesToWord?: boolean; /** Cooperative checkpoint for bounded non-yielding browser layout work. */ checkCancellation?: () => void; /** * Skip fragment-identity stamping at the end of paginate(). Callers that mutate the page tree * afterwards (running-story placement) and then call normalizePageMapFragmentIdentities() would * otherwise pay the whole forced-layout pass twice and discard the first result. Default: false. */ deferFragmentIdentities?: boolean; /** * Skip the "balloons" layout at the end of paginate(); the caller runs layoutMarkupBalloons() * itself once it has finished changing the page tree (the standalone export). Default: false. * Pages the balloon appendix adds then arrive only in that call's `appendedPages`; they are not * in the result paginate() returned, and a PageMap must be materialized after it. */ deferMarkupBalloons?: boolean; /** * Points to withhold from the body height available to specific physical pages (1-based page * number → pt). Only the fitting budget shrinks; the page's rendered bands do not move. The * standalone export uses it for its bounded corrective pass: when a finished page still clips * its body — its layout ran a few points past what the placement model predicted — the export * lays the document out again from pristine HTML with that page's budget reduced by the * overflow, so the offending block moves or splits onto the next page (issue #848). */ bodyBudgetReductionsPt?: Readonly>; /** * Incremental admission check invoked immediately before each physical page is allocated. * Export callers use this to enforce `finalPages` without constructing an over-limit DOM first. */ checkPageCount?: (prospectivePageCount: number) => void; /** @internal Export-only table layout, applied to each clone before its fit is measured. */ prepareTableFragment?: (table: HTMLTableElement) => void; /** @internal Export text preparation after body tables have their final column widths. */ prepareTableText?: (section: HTMLElement) => void; /** @internal Export text preparation inside a measured running-story band. */ prepareStoryText?: (story: HTMLElement) => void; /** Prepare attached note clones before measurement, splitting and final placement. */ prepareFootnoteText?: (note: HTMLElement) => void; /** Exact invalidation tokens used to materialize an authoritative PageMap with the result. */ layoutToken?: { documentVersion: number; rendererFingerprint: string; }; } /** * Pagination engine that converts HTML with pagination metadata * into a paginated view with fixed-size page containers. */ /** * Registry of footnotes by ID for per-page distribution. */ export type FootnoteRegistry = Map; /** * The top and bottom margins a block occupies in its parent's flow, in CSS px, AFTER CSS margin * collapsing through its first and last in-flow children (CSS 2.1 §8.3.1). getBoundingClientRect() * excludes such a collapsed-through margin, and getComputedStyle() reports only the element's own: * the converter wraps a table in an unstyled `div`, so the table's own top margin collapses * through the wrapper and occupies page height that neither of those reads accounted for. The * paginator's budget then fell a few pixels to a line short of the laid-out page, and the export * refused the clipped page (issue #848). * * A margin collapses with a parent's while the parent is an ordinary block box (display block or * list-item, overflow visible, not floated or absolutely positioned — anything else establishes * its own formatting context) with no border or padding on that side, the child is the parent's * first (last) in-flow block-level child, and no line content precedes (follows) it. For the * bottom edge the parent must also have an automatic height. Positive margins combine by maximum * and negative ones by minimum, as CSS collapses them. */ export declare function collapsedBlockMarginsPx(view: Window, element: HTMLElement): { topPx: number; bottomPx: number; }; /** A page-space box in client coordinates: left/top inclusive, right/bottom exclusive. */ export interface VisibleBox { left: number; top: number; right: number; bottom: number; } /** * Set by the paginator on floating content it promotes into the page box; the value lists its * original source ancestors' `data-source-anchor-id` values, separated by spaces. It survives into the * standalone export, whose offline re-verification measures through the same function. */ export declare const DRAWING_HOST_ATTRIBUTE = "data-docx-anchor-host"; /** * Set on a source-anchored element a floating drawing was promoted out of, so * {@link measureRenderedSource} looks up promoted drawings only for elements that have them. */ export declare const HOSTS_PROMOTED_DRAWING_ATTRIBUTE = "data-docx-hosts-promoted-drawing"; /** * Marks a block taller than its page that the paginator placed alone on a page. Word starts an * oversized exact row on a new page and clips at the paper edge; a footnote band retains its own * protected boundary (issue #1202). */ export declare const OVERSIZED_BLOCK_ATTRIBUTE = "data-pagination-oversized"; /** An oversized exact row responsible for this element's intentional vertical overflow. */ export declare function findOversizedExactRow(element: Element): HTMLTableRowElement | null; /** * Where a source-anchored element renders on `page`: `rect` is its layout box and `visible` the * part of it the page shows. Normally that is the element's own border box. An element the * paginator promoted floating drawings out of measures as the union of what it renders — its own * box (or, when that is empty, its descendants) and the drawings promoted out of it (linked by * {@link DRAWING_HOST_ATTRIBUTE}) — each clipped along its OWN ancestor chain, since a promoted * drawing sits outside the text column that clips its host (issue #849). Such a paragraph keeps a * line of its own when the drawing was its only content (issue #880), and its fragment still * encloses the drawing. Returns the element's own degenerate box when none of that renders. * * Fragment-identity normalization, PageMap materialization and the standalone export's offline * re-verification all measure through this one function, so they agree on which elements are * measurable and where. */ export declare const measureRenderedSource: (view: Window, element: HTMLElement, page: HTMLElement, pageRect?: DOMRect, textRect?: DOMRect, paperClip?: HTMLElement) => { rect: DOMRect; visible: VisibleBox; }; /** @internal Owned runtime code only; never inserts a script or enables document JavaScript. */ export declare function renderedSourceMeasurerExpression(): string; export declare class PaginationEngine { private stagingElement; private containerElement; private document; private view; private scale; private cssPrefix; private showPageNumbers; private pageGap; private commentColumnPlacement; private commentOverflow; private deferMarkupBalloons; private balloonOverflow; private markupMode; private markupBalloons?; private commentColumnWidthPt; private commentColumnGapPt; private fragmentParagraphs; private alignBaselines; private deferFragmentIdentities; private bodyBudgetReductionsPt; private cancellationCheckpoint?; private pageCountCheckpoint?; private prepareTableFragment?; private prepareTableText?; private prepareStoryText?; private prepareFootnoteText?; private createdPageCount; private layoutToken?; private hfRegistry; private footnoteRegistry; private footnoteSeparator; private footnoteContinuationSeparator; private commentMarginRegistry; private commentReturnLinks; private footnoteLayoutLikeWord8; /** The document's `compatibilityMode` (`data-docx-compatibility-mode`); NaN when unstated. */ private compatibilityMode; private pendingFootnoteContinuation; /** Per-section `w:pgNumType` (start / format), read off the section wrappers. */ private pageNumbering; private bodySectionDimensions; private lastPages; private expectedPageMapAnchorIds; private sourceClipBoxes; private inspectedSourceText; private sourceClipBoxSequence; private initiallyClippedText; private sourceTextPlacement; private lastClippedTextAnchors; private lastClippedTableContentAnchors; private linkedTextBoxOverflowAnchors; private state; private runningStyleSources; private runningStyleContexts; private runningStyleDefaults; private preparedRunningStories; private storyFrameExclusions; private runningStylePageCount; /** * Creates a new pagination engine. * * @param staging - The staging element or its ID containing the content to paginate * @param container - The container element or its ID where pages will be rendered * @param options - Pagination options */ constructor(staging: HTMLElement | string, container: HTMLElement | string, options?: PaginationOptions); /** * Runs the pagination process. * * @returns PaginationResult with page information */ paginate(): PaginationResult; /** One flow pass; field-dependent running bands are fixed for this pass. */ private paginatePass; /** Move overflowing columns' complete threads into ordinary flow; each column keeps a pointer. */ private appendCommentOverflow; /** Project converter comment headers, paragraphs and replies without their indivisible wrappers. */ private measureCommentBlocks; private initializeRunningStyles; private runningStylePageKey; /** The next pass reads these page-owned sources, including full text on split paragraphs. */ private updateRunningStyleContexts; /** Measurement and page cloning share these exact resolved stories within a pass. */ private prepareRunningStories; private checkpoint; /** * With "balloons" placement, lays out Word's markup area and balloons on the finished pages * (once; later calls return the first result). Runs inside paginate() unless deferMarkupBalloons * is set. Returns what could not be printed in full; undefined under other placements. */ layoutMarkupBalloons(): MarkupBalloonLayout | undefined; /** * A page after the last, in the last page's section, with no running stories: one more page of the * pagination, its result and its PageMap. */ private appendBlankPage; /** * Normalize visible fragment identities after a caller applies final standalone styles. This * deliberately runs before the stability barrier; materializePageMap is read-only so PageMap * measurement cannot mutate a tree after it was declared stable. */ normalizePageMapFragmentIdentities(): void; /** * Materialize the last completed browser layout as portable page-relative point geometry. * The caller supplies both invalidation tokens; this engine never guesses a document version * or renderer fingerprint. */ materializePageMap(documentVersion: number, rendererFingerprint: string): PageMap; private normalizeVisiblePageFragments; private storyForCanonicalAnchor; /** * Add canonical IDs from an addressable source subtree to the pre-pagination inventory. * Registry wrappers are excluded when scanning staging because selectable registry contents are * inventoried separately. Producers may explicitly mark content that has no visual substrate * with `data-page-map-exclude="true"`; native hidden semantics carry the same signal. */ private collectExpectedSourceAnchors; /** Source paragraphs intentionally unpainted by their authored box or placement, after final mapping. */ getSourceClippedTextAnchors(): readonly string[]; /** Source text or visuals cut by the paper edge in an authored fixed-width table. */ getClippedTableContentAnchors(): readonly string[]; /** The first paragraph of each linked text-box story that its last frame cannot hold. */ getLinkedTextBoxOverflowAnchors(): readonly string[]; private collectClippedTableContent; /** Where `rect` of `element` shows under every clip except the paper (`page`, sized `paper`). */ private visibleWithoutPaper; /** * Whether the paper alone hides `element`, as Word prints it (issues #1733, #1734): its layout * box has area and lies wholly outside the paper, every other clip would show it, and an * authored box carries it there — a fixed-width table, or a frame of a linked text-box story * placed from its source offsets. Anything else off the paper may be content the layout lost, * so it still fails completeness. An unlinked text box proves its own paragraphs off the paper * ({@link isInitiallyClippedText}); a linked story is distributed over its frames after they * are placed, so only the frames' placement comes from the source. */ private hiddenByPaper; private sourcePageFrame; private sourceTextPlacementBounds; private captureSourceTextClip; private isInitiallyClippedText; private isZeroHeightExplicitBreakCarrier; private isDeliberatelyUnrenderedSource; /** * Keep exactly one active bare-Unid editor anchor per source block. Presentation clones use * canonical source identity plus page/fragment qualification instead. */ private qualifyPageFragments; /** * Page flow clones source blocks while the hidden staging tree stays in the document. Any HTML * fragment target copied into a visible page would therefore resolve to its earlier hidden * source. Transfer target ownership to the page presentation after flow is complete; registry * and wrapper IDs that have no visible counterpart remain available to pagination internals. */ private transferVisibleFragmentTargets; /** Read each section's `w:pgNumType` off its wrapper (see {@link SectionPageNumbering}). */ private parsePageNumbering; /** * Fill in the page-number fields inside every page's cloned header/footer. * * A header/footer is authored once and cloned onto each page, so a PAGE field's single cached * result would otherwise show the same number on every page — the whole reason the converter * marks these. `data-field-format` (the field's own `\*` switch) wins over the section's format * when present, which is exactly how Word resolves the two. * * Runs after layout because NUMPAGES cannot be known before the last page exists. In documents * with running STYLEREF fields, the reconciliation pass also measures these page-number values * before allocating body space. Other documents retain the established late substitution. * * Ordinary cached fields are scoped to the CLONED header/footer regions. A page-number field in body text is * ordinary run content that the editor may make editable, and committing an edited block writes * back whatever text the DOM holds — rewriting it here would mean a body field commits a number * the document never contained. Legacy w:pgNum blocks are the exception: they have no cached * text and are explicitly non-editable, so their marked projection follows the current page * in every story while ordinary body fields keep their cached results. */ private substitutePageNumberFields; private substituteStoryPageNumbers; /** * Measures all content blocks in a section. */ private measureBlocks; /** Only converter comment shells may be split recursively; retain custom HTML intact. */ private prepareCommentGroups; /** Floated pictures participate in page fit even though normal block height excludes them. */ private floatingPictureCarriers; /** An indivisible picture must fit one page before paragraph fragmentation can help. */ private fitOversizedPictures; /** Fit to the actual page after a section transition or running field changes its body band. */ private fitBlockPicturesToPage; /** Reflow an over-wide table into its containing band without shrinking its text. */ private fitOverwideTables; /** * Flatten the converter's `section.endnotes > ol > li > p` presentation into * ordinary paragraph blocks. This preserves paragraph formatting and canonical * p:en/en:en identities while allowing the existing paragraph fragmenter to * split a long endnote across page boundaries. */ private measureSafeEndnoteBlocks; /** Render the CSS ordered-list formats emitted by the converter after an endnote is flattened. */ private formatOrderedListMarker; /** * Flows a multi-column (`w:cols`) section's children into CSS-multicol container * blocks. Word lays such a section out as N columns inside the same body extent; * a `column-count` container reproduces that geometry, and the paginator * then places each container as one ordinary measured block. A container grows * greedily until it would exceed the smallest page body available to the section. * Final continuous sections fill that height sequentially; other sections retain * balancing. A long columned section still splits across pages at block * boundaries. Each child lands in exactly one container, so anchors never * duplicate. An explicit page break child passes through as its own block, which * ends the current container and lets the normal flow logic turn the page. */ private buildColumnBlocks; /** Keep Word's paragraph space-before in the ordinary inter-block spacing budget. */ private liftColumnSpaceBefore; /** A height-constrained multicol box overflows horizontally when it needs another column. */ private columnContainerOverflows; /** CSS may break a column's table internally; protect row features it cannot model. */ private canFragmentColumnTable; /** Reflow a column child stream against the actual remaining body band. */ private reflowColumns; /** * Measures one element in the same hidden staging context used for the source blocks. * This is intentionally DOM-based: table row heights cannot be inferred from individual * rows because wrapping and collapsed borders change the height of a fragment. */ private measureElement; /** * Returns the contiguous keep-with-next chain beginning at a block. * * A hard page break or a page-break-before directive is stronger than a * keep-with-next directive, so it terminates the chain. The caller only * keeps a chain together when the whole chain or a valid first fragment can fit on a fresh page. */ private getKeepWithNextChain; /** * Measures the visible body height of a keep-with-next chain using the same * collapsed-margin rules as normal block placement. The trailing margin is * intentionally excluded, matching the individual block fit check. */ private measureKeepWithNextChainHeight; /** Word paragraphs render as `p`, or as `h1`–`h6` when their style has an outline level. */ private isWordParagraphElement; /** * Whether a laid-out block's top margin is Word paragraph space-before: a paragraph's own, or * that of the box around a bordered run of paragraphs, which carries the run's (issue #1677). */ private hasParagraphSpacing; /** * The extra leading an auto line-spacing multiple puts below the text of a laid-out paragraph's * last line. Word puts that leading below the text (issue #908), and a page's last line needs * only its text height: the leading may run past the bottom margin (issue #1571). Only text the * converter's lift holds at the top of its line box qualifies; a run laid out with CSS's split * leading would paint below its text height, and pictures, bottom borders and padding keep the * full line. The smallest run bounds the leading below every run's text. Word centres a grid * line's text instead, so half of that line's extra height lies below its text (#1551). Mixed text's * line metrics carry their own lines, of which only a grid line's leading qualifies. */ private lastLineTrailingLeadingPt; /** * The height a block needs above the bottom of the page; see `MeasuredBlock.trailingLeadingPt`. * Before compatibility mode 15 the leading may also run under a note band; from mode 15 the band * clears the full line box, and only the page foot lets the leading run past (#1751). */ private fitHeightPt; /** The leading a block placed in `availablePt` lets run past: its last line fits only by its text height. */ private droppedLeadingPt; private shouldSuppressPageTopSpacing; /** * Resolves the part of a block's top margin that consumes the current page. * * In Word's native DOCX layout, paragraph space-before is suppressed when a paragraph is the * first body block on a later page of the SAME section. The first page of a document/section is * the exception and keeps its spacing. Tables and other block margins are not paragraph spacing, * so they continue to use the ordinary CSS collapsing rule. */ private effectiveBlockMarginTop; /** Clone a source block with the same page-top spacing decision used by the height budget. */ private cloneBlockForPage; /** Horizontal body geometry follows the source section, independently of the page's bands. */ private horizontalSectionDimensions; /** Use the same ordinary block containers for physical pages and fragment measurement prefixes. */ private appendSectionContent; private hasFlowExclusion; /** * Finds footnote references introduced by a sequence of blocks, preserving * document order and excluding references already assigned to the page. */ private collectNewFootnoteIds; /** * The shortest body available to a section's first, default, or even page. * A row fragment must fit every variant, otherwise a later header/footer could * send it through the oversized-block fallback again. */ private smallestEffectiveContentHeight; /** * Builds a clone of a simple table wrapper containing a contiguous run of rows. * The caller supplies complete vertical-merge groups: no rowspan crosses a * fragment boundary. * Horizontal merges (colspan) are confined to their own row. `repeatedRows` (the table's * header rows, on a continuation) are copied in first, marked as repeats. */ private createSimpleTableFragment; /** * The row counts after which a table may split: a boundary is safe only after every cell * starting above it has ended. Overlapping merges in different columns extend the same * indivisible group; HTML rowspan=0 extends through the remainder of the row section. The last * entry is always `rows.length`. */ private tableRowGroupEnds; /** * How many leading rows are the table's header rows (`w:tblHeader`), which a split repeats at * the top of each continuation: the run must end at a safe boundary and leave rows to carry. */ private leadingHeaderRowCount; /** * Splits an oversized, ordinary table at row boundaries. This only participates * in the existing oversized-block fallback; unsupported tables keep the previous * overflow behavior rather than risking broken table semantics. * * Word repeats a table's leading run of header rows (`w:tblHeader`) at the top of every page * the table continues on, whatever their height rule (issue #1171), so each continuation * starts with copies of them. When the copies leave no room to split the table, it splits as * it did without them (`repeatHeaderRows` false). */ private trySplitSimpleOversizedTable; /** * A vertical merge taller than a fresh page has no legal whole-group boundary. Materialize * its occupied grid slots as rows: source content stays once at its starting row and empty * presentation cells carry the remaining span. The ordinary row/cell fragmenter then owns * continuation. Fitting merges, repeated-header groups and authored exact-height rows stay intact. */ private recoverOversizedMergedGroups; /** * Lowers the minimum of each `atLeast` row whose minimum alone makes the row taller than * `maximumHeight` until it fits, and reports whether any changed. Content still sets its height. */ private capMinimumRowHeights; /** * Cuts a row taller than a page into rows that each fit one (`fits`), as Word breaks such a row * (issue #1202): every cell keeps, in order, the blocks it holds, and a cell whose blocks are all * placed is left empty. A block taller than a page is a piece of its own, marked `oversized`. An * exact-height row is not cut: Word starts it on a new page and clips it there. Neither is a row * whose cells hold anything but blocks. */ private splitRowAtBlocks; /** * DOM endpoints that can finish a paragraph fragment. The flattened UTF-16 * offsets are checked against the browser's Unicode grapheme segmenter, so a * formatting-run boundary can never bisect a surrogate pair, combining * sequence, or joined emoji. NBSP/word-joiner boundaries remain indivisible. * PAGE/NUMPAGES field results are atomic because splitting their marker would * make later substitution duplicate or replace only half of the field. */ private paragraphFragmentEndpoints; /** Browser-native UAX #29 boundaries; null keeps older runtimes conservative. */ private graphemeBoundaryOffsets; /** * Conservative UAX #14/CSS wrapping opportunities used for synthetic page * boundaries. In particular, a formatting-run boundary is not itself a word * boundary, and Japanese opening/closing punctuation stays with its pair. * Arbitrary grapheme breaks are admitted only when the paragraph's CSS asks * the browser to wrap anywhere. */ private isLegalParagraphLineBoundary; /** Never fragment across characters whose line-break meaning is explicitly non-breaking. */ private isNonBreakingTextBoundary; /** * Without Intl.Segmenter, admit only an all-ASCII boundary. This still * fragments ordinary prose while refusing to guess about Unicode clusters. */ private isConservativeFallbackTextBoundary; /** * Whether a range retains visible text or a whole inline image. */ private hasVisibleFragmentContent; private hasVisibleText; /** * Text, hard line breaks and whole inline images share Range fragmentation. * Out-of-flow objects and richer inline boxes retain their dedicated layout rules. */ private canFragmentParagraph; /** * Shared structural gate for body and note paragraph fragmentation. Footnote * first paragraphs are inline beside their marker, so that one known layout * context may opt into an inline root while retaining every descendant and * break-safety restriction used for body text. */ private canRangeFragmentParagraph; /** The converter's automatic-spacing lift moves ink without changing inline line boxes. */ private hasRangeFragmentSafePosition; /** A single edge picture can exclude space from the beginning of its source fragment. */ private canReflowEdgePicture; private isLeadingDrawing; /** Resolve the float while attached, retaining the picture at its original Range position. */ private prepareBodyEdgePictures; /** A cloned prefix excludes only pictures actually retained by that prefix's raw Range. */ private rebuildEdgeExclusion; private edgeExclusionsMatch; /** Fixed-base anchors follow their source Range. Edge pictures retain that same ownership * while a separate empty float reflows the destination fragment from its beginning. */ private fragmentDrawingBoxes; /** * Boxes that move whole: an inline block (a converter shape, text box or ruby pair) lays out its * content in its own formatting context, and converter tab segments, inline math and fitted text * are likewise single units. Range endpoints never enter one, so it keeps its inner layout. */ private rangeAtomicInlineBoxes; /** * A range clone preserves nested inline formatting exactly. Anything that establishes its own * box/layout context is deferred until a future fragmenter can model it accurately. Callers * must invoke this while the paragraph is attached to the styled document. */ private hasRangeFragmentSafeLayout; /** * Whether the text after `endpoint` begins a new visual line of the laid-out `paragraph`: the * nearest glyph after it sits lower than the nearest glyph before it by more than half a line. * A raised citation number in the middle of a line sits higher, so it stays on its line. */ private startsVisualLine; /** The first/last painted text glyph in a range, excluding whitespace and zero-width marks. */ private rangeEdgeGlyph; private rangeHasMultipleTextLines; /** * The boxes a paragraph opens with before its first text: its list marker, a note's number, * and any box that holds no text, such as the tab that follows either. */ private leadingAtomicBoxes; /** * Builds one range-cloned paragraph fragment. Only the leading fragment keeps * the source paragraph's addressability; continuations must not duplicate an * id/data-anchor in the rendered document. */ private createParagraphFragment; /** * Range clones repeat an inline ancestor when the split lands inside it. Keep * semantic wrappers (links, comments, formatting) on both sides, but retain a * duplicated HTML/editor identity only on the leading fragment. Targets that * occur wholly after the split are absent from `head` and remain on `tail`. */ private reconcileFragmentIdentities; /** * Range-clone the largest safe prefix accepted by `fits`. The measurement * policy stays with the caller, allowing body blocks and note bands to share * one DOM fragmenter while measuring in their respective layout contexts. */ private splitParagraphAtLargestFit; /** * The converter's box around a run of paragraphs that share one border (`w:pBdr`): a `div` whose * element children are all Word paragraphs and that draws a border. `element` must be laid out. */ private isBorderGroup; /** * Splits a bordered paragraph group where Word breaks it across pages (issue #1202): after the last * paragraph that fits, or inside the paragraph that does not, as an ordinary paragraph splits. Word * leaves the border open at the break: the first part has no bottom border and the rest no top * border, so each part keeps its side borders. A group that cites notes, or keeps its lines or its * next paragraph, keeps the whole-block fallback. */ private tryFragmentParagraphGroup; /** Split paragraph groups in the caller's context, retaining every comment shell around each candidate. */ private splitParagraphGroup; /** * Splits a simple paragraph at the largest DOM Range endpoint that fits the * currently available body space. The caller then processes the tail normally, * allowing it to fragment again on later pages when necessary. */ private tryFragmentParagraph; /** Fill the remaining body band without separating a citation from its note. */ private tryFragmentTable; /** * Parses the header/footer registry from the staging element. * Also measures heights during parsing for lazy-loading compatibility. */ private parseHeaderFooterRegistry; /** * Parses the footnote registry from the staging element. */ private parseFootnoteRegistry; /** Read Word's optional normal and continuation separator stories. */ private parseFootnoteSeparators; /** Append the exact separator story selected for this initial/continued note band. */ private appendFootnoteSeparator; /** * Strip every identity from a copy the paginator paints again: element ids and anchor names, * editor anchors, note, comment and annotation ids, and internal links, so the copy is not a * second bookmark target, comment, note citation or annotation and cannot be edited. * `keepSourceAnchors` keeps the canonical source identity, for a copy (a repeated table header * row) that the PageMap maps as one more fragment of its source. */ private makePresentationCopyInert; /** Parses the hidden source notes used to render paginated margin comments. */ private parseCommentMarginRegistry; /** * Extracts footnote reference IDs from an element. */ private extractFootnoteRefs; /** Clone a note child for the continuation queue with its original selector position. */ private cloneFootnoteElementForContinuation; /** Remove identities that belong only to the initial registry presentation shell. */ private makeContinuationShellInert; /** * Build the exact continuation shape shared by measurement and paint. * * Keep the source `.footnote-item > .footnote-content` ancestry: document * CSS, inherited direction/language, and custom classes frequently target * those shells. Only a number rendered beside the content and the initial * HTML/editor identities are omitted; the converter's number travels inside * the first paragraph (issue #1130). A hidden sentinel preserves * `p:not(:first-of-type)` in document CSS for a page whose first carried * element was a later source paragraph; the generated stylesheet has no * first-paragraph rule any more. */ private createFootnoteContinuationWrapper; /** Build the exact partial-note item shape shared by measurement and paint. */ private createPartialFootnoteItem; /** * Where a note measurement tree is attached. * * A note band is reserved from a measurement and then painted; if the two * happen under different inherited typography the painted notes overflow the * reserve, which is the invisible clipping this engine exists to avoid. The * registry lives in the staging tree but a band paints inside the output * container, so measure there. The host is never a page box, so a page's * `zoom` cannot scale a reserve that is accounted for in unscaled points. */ private noteMeasurementHost; /** * Measures the height of footnotes for given IDs (in points). * Creates a temporary container to measure the footnotes. * @param footnoteIds - IDs of footnotes to measure * @param contentWidth - Width for measurement * @param continuation - Optional continuation content to include first */ private measureFootnotesHeight; private blockTable; /** * Split a body or note table at the largest complete row-group boundary that fits, preserving * vertical merges and repeated headers. Null if no group fits, unless `forceFirst` requests * the note-only liveness fallback. A wrapper holding only the table is retained. */ private splitTableAtRows; private isEmptyBookmarkTarget; /** A terminal flow paragraph can keep this row with its successor. Nested tables own their keeps. */ private rowKeepsWithNext; /** Split a table between rows, or inside the first row when no complete row fits. */ private splitTableContent; /** Partition a carried note, advancing even when its first indivisible element is oversized. */ private splitContinuationForPage; /** * Whether every note in `footnoteIds` can begin in a note band of `availableHeightPt` that * already holds the page's packed payload: each whole except the last, which may be split * provided at least its first line fits. Mirrors the placement loop's decisions without * changing any page state, so the paginator can move a citation to the next page instead of * separating it from its note (Word starts a note on the page that cites it). */ private notesCanStartOnPage; private notesStart; /** * Splits a footnote element into parts that fit within the available height. * Returns the elements that fit and the elements that need to continue. */ private splitFootnoteToFit; /** * Adds footnotes to a page container, including continuation content. */ private addPageFootnotes; /** Select the section's first/odd/even header from its one-based page position. */ private selectHeader; /** * The story KIND (`"first"` / `"even"` / `"default"`) a page position selects — the same * decision {@link selectHeader} / {@link selectFooter} make, named rather than resolved to * an element, so a page can advertise which OOXML story it is showing. */ private storyKindFor; /** Select the section's first/odd/even footer from its one-based page position. */ private selectFooter; /** * The header, body, and footer bands for one page position. * * The single owner of "where does anything sit vertically on this page" — placement in * {@link createPage}, the body budget the flow loop spends, and the note area's anchor all * read it, so those three cannot disagree about where the body ends. * * Within a flow pass, story values and heights are fixed. STYLEREF documents reconcile page * ownership between passes; placement and body budgeting consume the same prepared stories. */ /** The body height a physical page may fill: its body band less any caller-requested reduction. */ private bodyBudgetPt; private getPageBands; /** * The measured height of the running story this page position selects, mirroring * {@link selectHeader}/{@link selectFooter}. Zero when the page has no such story. */ private selectStoryHeight; /** Carry the selected header's overhanging frame exclusion into body layout, without its text. */ private headerFramePrefix; private frameExclusionRectangles; private frameExclusionRectangle; private frameExclusionPolygon; /** Probe ordinary flow without changing the preceding paragraphs' float wrapping. */ private unclearedBlockTop; /** Lay out each source line in the intervals left by the union of frame rectangles. */ private layoutFrameParagraph; private prepareFrameExclusions; /** * Measures the content height of a header or footer element. * * This is what tells {@link resolvePageBands} whether the story stays inside its margin or * pushes the body, so it must measure the story ALONE — any padding added here would have to * be added to the rendered band too, and the two drifting apart is exactly how a header * silently starts overlapping body text. */ private measureHeaderFooterHeight; /** * Flows measured blocks into page containers. * Implements a single-pass, forward-only algorithm that is compatible with future lazy loading. * Supports footnote continuation - long footnotes can split across pages. */ private flowToPages; /** * Strip block addressing from a header/footer node cloned into a page box. * * A running story is authored ONCE and cloned onto every page, so the clones all carry the same * `data-anchor` — on this document, 42 page boxes claiming one footer paragraph. Left editable, * committing any one of them writes back through that single shared anchor, and the per-page * page-number substitution makes it worse: each clone shows a DIFFERENT number, so a commit * writes that page's number into the story as literal text and destroys the PAGE field. * * Page-box header/footer content is presentation. The docked editing bands * (`editor-headerfooter.ts`) are the addressable affordance, and they exist precisely because a * cloned node cannot be uniquely addressed. */ private makeClonedStoryInert; /** Keep repeated note identities inert; resolve their return links after every page exists. */ private makeClonedMarginCommentInert; /** A return link may target only one actual rendered reference, including on a later page. */ private activateCommentReturnLinks; /** Freeze inherited presentation before moving content out of its source ancestors. */ private preserveInheritedPresentation; /** Keep the visible content of emptied paragraphs, cells and tables linked to its source. */ private promoteSourceContent; /** Keep a raised inline text box's paint above the body band without moving its flow slot. */ private positionRaisedInlineTextBoxes; /** Measurement and paint read the same authored offset, before placement mutates inline styles. */ private frameHorizontalPosition; /** Resolve legacy paragraph frames after their ordinary anchor paragraphs have flowed. */ private positionTextFrames; /** Flow one source story through its declared, already positioned text-box frames. */ private flowLinkedTextBoxes; private linkedTextBoxFits; private prepareSourceTextBoxSizes; private sizeDrawingAnchor; private prepareShapeClearance; /** * Resolves floating DrawingML objects after their anchor paragraphs have landed on a page. * * The converter deliberately carries the OOXML bases and offsets as data instead of flattening * them into CSS: page/margin/column bases belong to the page, while paragraph/line/character * bases belong to the laid-out anchor. Once both coordinate systems exist, promote the object * from the clipped text column into the page box and position it in one shared point space. */ private positionDrawingAnchors; private anchorNumber; private horizontalAnchorReference; private verticalAnchorReference; private resolveAnchorAxis; /** Charge a physical page before any page-owned partitioning or DOM allocation. */ private admitPageAllocation; /** * Creates a page container element. */ private createPage; } /** * Convenience function to paginate HTML content. * * @param html - HTML string with pagination metadata * @param container - Container element or ID where pages will be rendered * @param options - Pagination options * @returns PaginationResult * * @example * ```typescript * const html = await convertDocxToHtml(docx, { paginationMode: PaginationMode.Paginated }); * * // Create a container for the paginated view * const container = document.getElementById('viewer'); * * // Parse and paginate * container.innerHTML = html; * const staging = document.getElementById('pagination-staging'); * const pageContainer = document.getElementById('pagination-container'); * * const engine = new PaginationEngine(staging, pageContainer, { scale: 0.8 }); * const result = engine.paginate(); * * console.log(`Document has ${result.totalPages} pages`); * ``` */ export declare function paginateHtml(html: string, container: HTMLElement | string, options?: PaginationOptions): PaginationResult; //# sourceMappingURL=pagination.d.ts.map