# Page layout

> Page sizes, orientation, margins, pagination, headers and footers with page numbers, the ruler, zoom and the web layout of Birch UI Document Editor.

In page layout the document is shown as separate sheets of paper with margins, a header and a footer, exactly as it will print. **Web layout** removes the pages and lets the text fill the width, which suits narrow screens and drafting.

```ts
editor.setLayout('web');
editor.setLayout('page');
editor.setZoom(1.25);
```

## Page setup

```ts
editor.setPageSetup({
  size: 'A4', // 'A3' | 'A4' | 'A5' | 'Letter' | 'Legal' | 'Executive' | { width, height } in points
  orientation: 'landscape',
  margins: { top: 56.7, right: 56.7, bottom: 56.7, left: 56.7 },
  headerDistance: 28.35,
  footerDistance: 28.35,
  differentFirstPage: true,
});
```

### Mirror margins and vertical alignment

```ts
editor.setJSON({ ...editor.getJSON(), settings: { mirrorMargins: true } });
editor.setPageSetup({ margins: { top: 72, right: 54, bottom: 72, left: 90 }, gutter: 18, verticalAlign: 'center' });
```

With **Mirror margins** (Page setup, Margins tab; `settings.mirrorMargins`) the left margin is the inside margin and the right margin the outside margin of a book: pages with an even page number swap them, and the gutter stays on the inside. The text, the header and footer, the footnotes, column rules, page borders and the ruler all follow, on screen, in print and in PDF. A paragraph, list or table that continues on the next page moves over with it.

`verticalAlign` (Page setup, Layout tab) places the text of a page that is not full: `'top'` (the default), `'center'` or `'bottom'` of the text area, measured after the footnotes of the page. It is a section property, so a title page can be centred while the rest of the document starts at the top. `'justify'` spreads the blocks of a page between the top and the bottom margin: the free height is divided evenly above every paragraph, table and list that starts on the page after the first. The last page of a section is not spread, and neither is a page with more than one column. The editor, print and both PDF exports draw it the same way.

All values are in points. The **Page setup** dialog shows margins in centimetres for metric paper and inches for Letter, Legal and Executive. Page setup is part of `DocumentData.page` and maps to the section properties of a DOCX file.

## How pagination works

The editor measures the height of each block and, for blocks that cross a page boundary, the height of each line or table row. A DOM-free layout engine then decides where pages break and inserts spacers that move the following content to the top of the next sheet. Text stays in one editable flow, so selection, copy and paste, find and undo work across page boundaries.

The engine follows Word's rules:

- **Paragraphs split between lines**, with widow and orphan control. `keepLines` keeps a paragraph whole and `widowControl: false` turns the control off for one paragraph. The last line before a page split of a justified paragraph stays justified.
- **Keep with next**: headings, titles and paragraphs with `keepWithNext` move to the next page with the paragraph that follows them.
- **Page break before**: paragraphs with `pageBreakBefore` always start a page, and page breaks (<kbd>Ctrl</kbd>+<kbd>Enter</kbd>) end one.
- **Tables split between rows**, and header rows repeat at the top of each page. A row that is taller than the space left splits between the lines of its cells, unless the row has `cantSplit`; the header row is repeated above the second part of a split row as well.
- **Lists split between items**, including between the nested items of a multilevel list.
- **Footnotes** are set at the bottom of the page that holds their reference, under a separator line, and reduce the room for body text on that page. This also holds for references inside table cells and list items. A note that does not fit continues on the next page. Double-click a note to edit it in place.
- **Endnotes** are listed after the last paragraph and paginated like any other content: the list starts where the text ends and continues over as many pages as it needs. With **End of section** chosen in the [Footnote and endnote options](https://docs.birchui.com/document/dialogs.md#footnote-and-endnote-options), the endnotes of each section follow that section instead.

### Spacing rules

The vertical rules follow Word rather than CSS, because they decide where every page breaks:

- **Line spacing is a multiple of the font's own line height.** "Single" is the ascent, descent and line gap of the font, so 11 pt Calibri at 1.15 gives 15.4 pt lines, not 12.65 pt. The editor measures the ratio of each font in the browser.
- **Space after and space before do not add up.** Between two paragraphs the larger of the two applies. The same holds between paragraphs inside list items and table cells.
- **Contextual spacing** ("don't add space between paragraphs of the same style"), from a paragraph or from its style, removes the space between neighbours of the same style, also across the levels of a list.
- **Space before is dropped at the top of a page** when a paragraph is moved there by a page break; it still counts when deciding whether the paragraph fits on the page it came from.
- **Space after may hang below the last line of a page.** A paragraph or list item fits when its text fits.
- **The paragraph mark after a nested table** at the end of a cell takes no height.
- **List indents** come from the numbering definition of an imported document (`indentLeft` and `hanging` per level) instead of a fixed step.
- **A list item that keeps with the next** (its paragraph or style has "keep with next") moves to the next page together with the item after it.
- **Line heights are whole twentieths of a point.** A line of 11 pt text at 1.15 is 14.5 pt high, not 14.5475 pt, as in LibreOffice. Over a page the difference is about two points, which decides whether the last row of a table still fits.
- **Table borders take their real width.** A browser draws a half-point border one device pixel wide. The editor takes the difference out of the row, so a row is as high at 100% zoom on a plain screen as on a high-density one.
- **Nothing is added below a table.** The paragraph after a table starts at the table's last border plus its own space before.
- **A page break needs room for its line.** A break in a paragraph of its own takes one line on the page it ends. When that line does not fit, the break moves to the next page and leaves it empty, as it does in Word.
- **Superscripts and subscripts do not make a line taller.**
- **Space after may hang when a paragraph is kept with the next.** A picture with "keep with next" stays on the page when the text of its caption fits.
- **Hidden styles are applied.** A style that Word hides from its gallery, such as Caption, formats the paragraphs that use it and stays out of the style list.

### Layout compatibility

These rules arrived in one release and changed page counts: a report that had 300 pages has 350. `layoutCompatibility` chooses between them and the earlier model.

```ts
const editor = createDocumentEditor(host, { layoutCompatibility: 'legacy' });
editor.update({ layoutCompatibility: 'word' });
```

| Value | Line height | Space between paragraphs | Contextual spacing | Space before at the top of a page |
| --- | --- | --- | --- | --- |
| `'word'` (default) | multiple of the font's own line height, in twentieths of a point | the larger of the two | applied | dropped |
| `'legacy'` | multiple of the font size | both are added | ignored | kept |

`'word'` also takes real border widths for table rows, puts no space below a table, keeps a line for a page break and stops superscripts from stretching a line. `'legacy'` leaves these as they were: 8 pt below every table and a page break without height.

Use `'legacy'` while stored page references or tests still depend on the earlier pagination. The list indents and the other fixes of that release apply in both modes, so `'legacy'` is close to the earlier page counts and not guaranteed to match them.

### Page number fields in the text

`PAGE`, `NUMPAGES`, `SECTIONPAGES` and `PAGEREF` fields in body text show the page they are on, the page count, the pages of their section and the page of a bookmark. They are refreshed whenever the layout completes, so they follow edits. The number format of the section and the `\* roman` style switches are honoured.

```ts
editor.getPageText(2); // the body text of page 2, one line per block
```

### Sections and columns

A `section_break` node starts a new section with its own page size, orientation, margins, headers and footers, page-number format and numbering restart (`attrs.page`, `attrs.headers`). The section type is `nextPage`, `continuous`, `evenPage` or `oddPage`; even and odd page sections insert a blank page when needed. `page.columns = { count, gap, separator }` flows a section in columns. Paragraphs split between columns line by line (with the same widow and orphan control as between pages), tables row by row and lists item by item; the columns are balanced before a continuous break and on the last page, and a column break moves the following text to the next column. When the columns have different widths, blocks move between them whole, because a line set for one width cannot continue in another.

### Large documents

Documents with a few hundred blocks or more are laid out incrementally. The first screen is measured at once and the rest in idle slices; blocks away from the viewport are skipped by the browser with `content-visibility`, and page frames exist only near the viewport. After an edit only the changed block is measured and pagination resumes from the page before it.

```ts
await editor.whenLayoutReady(); // page count is exact from here
editor.on('layoutComplete', ({ pageCount, durationMs }) => {});
editor.getPageInfo(3); // { number, label, section, width, height, orientation, columns, footnotes, … }
editor.getLayoutStats(); // { pages, blocks, measured, cacheHits, lastLayoutMs, virtualized, … }
```

Set `virtualize: false` to lay out every block eagerly, or `virtualize: true` to force the incremental path. `getPageCount()` and `getCurrentPage()` return the counts used by the status bar, and the `pageCountChange` event fires when the number changes. `relayout()` measures everything again, which is useful after you change fonts loaded by your page.

The engine itself is exported as the DOM-free `paginate(blocks, options)` function, which takes block, line and row heights and returns the page breaks. You can use it to estimate page counts on a server.

Pagination is measured in the browser, so a document's page count matches Word's when the same fonts are available. If a font used by the document is not installed, the browser substitutes one with different widths and line breaks can move. Ship the fonts your templates use as web fonts for consistent results.

### Floating pictures and shapes

A picture or shape with wrapping (`square`, `tight`, `through`, `topBottom`, `behind`, `inFront`) is anchored to its paragraph and moves with it.

- **Square, tight and through** objects at the left or right edge of the column have text beside them, continuing into the following paragraphs for as long as the object reaches. Tight and through follow the wrap polygon of the file, or the outline of a picture with transparency when there is none.
- **An object inside the column has text on both sides.** This applies when the object is centred or stands at least 72 px from the left edge. The editor breaks the affected lines itself: it measures every word, fills the room left of the object, continues right of it and ends the line where the column ends. A side narrower than 72 px stays empty. `wrapSide` in the anchor limits text to `'left'`, `'right'` or the `'largest'` side. Square wrapping keeps text out of the bounding box; tight and through follow the wrap polygon line by line, and through also lets text into hollows of the polygon.
- **Top and bottom** objects keep text above and below only. **Behind** and **in front** objects take no room.
- **Vertical position** relative to the page or the margin, as an offset or as top, centre or bottom, is honoured for objects that end up at or below their anchor paragraph.
- A paragraph is kept on the same page as an object that hangs below it.

Text on both sides is laid out in every alignment, in right-to-left paragraphs and in table cells. Lines beside the object are not justified, a paragraph that continues on the next page runs the full width there, and web layout shows the object as a plain float. See [Limitations](https://docs.birchui.com/document/limitations.md).

### How close is the layout to a word processor?

`e2e/tests/document-fidelity.spec.ts` opens every file of the DOCX corpus in the editor in Chrome and compares the result with the PDF that LibreOffice makes from the same file, with the same fonts installed. The numbers of the last run are on the [DOCX page](https://docs.birchui.com/document/docx.md#layout-compared-with-libreoffice).

## Headers and footers

Headers and footers are small documents of their own, stored in `DocumentData.header`, `footer`, `firstHeader` and `firstFooter`. Double-click a header or footer area on any page to edit it, or focus it and press <kbd>Enter</kbd>; press <kbd>Escape</kbd> or click outside to finish. `editHeaderFooter('header' | 'footer')` opens the editor from code.

Insert **Page number** and **Number of pages** fields from the field menu, or with `exec('insertPageNumber')` and `exec('insertPageCount')`, to build "Page 3 of 12". The fields are filled in on every page and export as Word `PAGE` and `NUMPAGES` fields.

With `differentFirstPage: true` the first page uses `firstHeader` and `firstFooter`, which is common for letterheads and cover pages.

## Watermark

**Layout → Watermark** puts a text or a picture behind the text of every page. A text watermark has a text, a diagonal or horizontal layout, a colour and an opacity; a picture watermark has a picture file (PNG, JPEG, GIF, WebP or SVG), a scale and a washout switch.

```ts
editor.setWatermark('DRAFT');
editor.setWatermark({ text: 'CONFIDENTIAL', rotation: 0, opacity: 0.2, color: '#c00000' });
editor.setWatermark({ text: '', image: 'data:image/png;base64,…', washout: true }); // scale: 1.5 for 150%
editor.setWatermark(null);
```

In DOCX the watermark is the shape Word puts into the header for it (`PowerPlusWaterMarkObject` for text, `WordPictureWatermark` for a picture, with the picture as a media part), so Word shows it under **Design → Watermark** and can change or remove it. A watermark in a Word file is read from the header into `watermark` and no longer shows as an object inside the header. A document without a header gets an empty default header to carry the watermark. `image` must be an embedded `data:image/…` URL; an address on the network is refused.

## Ruler

The ruler above the page shows the page width in centimetres or inches with the margins shaded. Its three markers are the first-line indent, the left indent and the right indent of the current paragraph. Drag them, or focus one and use the arrow keys (<kbd>Shift</kbd> for finer steps); each marker is a slider for assistive technology. Hide the ruler with `ruler: false`.

## Printing and PDF

`print()` prints the pages you see: the print document holds one fixed-size box per page with the same line breaks, headers, footers, footnotes and watermark, and a CSS `@page` size per section, so the browser does not paginate again. `getPrintHtml()` returns that document as a string.

`exportPdf(options)` returns a `Promise<Blob>` with a vector PDF written in the browser. Text positions come from the laid-out pages, so the PDF matches the screen page for page; text is selectable and searchable, links and a heading outline are included.

```ts
const blob = await editor.exportPdf({ title: 'Master Services Agreement' });
```

The PDF uses the standard Helvetica, Times and Courier fonts as stand-ins for sans-serif, serif and monospaced families and scales each word to its measured width, so line breaks and justification stay the same while letter shapes can differ from the screen font. Characters outside Windows-1252 (Greek, Cyrillic, CJK, Arabic and others) need a TrueType font passed in `pdfFonts: [{ family, data, bold?, italic? }]`; the whole font file is embedded. Right-to-left runs are written in visual order without shaping. Watermarks, rotated or cropped pictures and CSS-generated list labels of multilevel lists are not drawn; pictures that are not PNG or JPEG are embedded as bitmaps. `layoutToPdf(layout)` is the DOM-free writer behind it and also runs in Node.js. See [PDF export and print](https://docs.birchui.com/document/pdf-and-print.md).
