# Printing and page setup

> Page setup, print areas, repeated title rows, page breaks, headers and footers, printing with the browser, and standalone print HTML for PDF pipelines.

Each sheet has its own page setup. It is saved in the workbook JSON and round-trips to xlsx. Users change it on the [Page Layout tab](https://docs.birchui.com/spreadsheet/toolbar.md#the-page-layout-tab) of the ribbon or in the page setup dialog (File > Page setup).

```ts
sheet.setPageSetup({
  orientation: 'landscape',
  paperSize: 'a4',
  margins: { top: 0.75, bottom: 0.75, left: 0.5, right: 0.5 },
  printArea: 'A1:H60',
  printTitleRows: '1:2',
  fitToWidth: 1,
  gridlines: true,
  footer: 'Page &P of &N, &A',
});
sheet.setPageBreak('row', 31);
sheet.print();
```

**`PageSetup`** (interface from `@birchui/spreadsheet`, full reference: https://docs.birchui.com/api/spreadsheet.md)

```ts
interface PageSetup
```

| Property | Type | Description |
| --- | --- | --- |
| `orientation?` | `'portrait' \| 'landscape'` |  |
| `paperSize?` | `PaperSize` |  |
| `scale?` | `number` |  |
| `fitToWidth?` | `number` |  |
| `fitToHeight?` | `number` |  |
| `margins?` | `PageMargins` |  |
| `printArea?` | `string` |  |
| `printTitleRows?` | `string` |  |
| `printTitleColumns?` | `string` |  |
| `gridlines?` | `boolean` |  |
| `headings?` | `boolean` |  |
| `centerHorizontally?` | `boolean` |  |
| `centerVertically?` | `boolean` |  |
| `header?` | `string` |  |
| `footer?` | `string` |  |
| `rowBreaks?` | `number[]` |  |
| `columnBreaks?` | `number[]` |  |

| Property | Meaning |
| --- | --- |
| `orientation`, `paperSize` | `'portrait'` or `'landscape'`; `'letter'`, `'legal'`, `'tabloid'`, `'a3'`, `'a4'` or `'a5'`. |
| `margins` | In inches, as in Excel. |
| `printArea` | The range to print. Without it the used range is printed, including pictures and charts. |
| `printTitleRows` | Rows repeated at the top of every page, such as `'1:1'`. |
| `printTitleColumns` | Columns repeated at the left of every page, such as `'A:A'`. |
| `scale` | A percentage. |
| `fitToWidth`, `fitToHeight` | The number of pages wide and tall the print should fit into. Either may be left out to fit one dimension only. Fit-to overrides `scale` and never enlarges. |
| `gridlines`, `headings` | Print cell gridlines, and row numbers and column letters. |
| `centerHorizontally`, `centerVertically` | Centre the sheet on the page. |
| `header`, `footer` | Text with Excel codes: `&P` page, `&N` pages, `&A` sheet name, `&F` title, `&D` date, `&T` time. `&L`, `&C` and `&R` start the left, centre and right sections. |
| `rowBreaks`, `columnBreaks` | Manual page breaks. A value of `30` starts a new page at row 31. |

`setPageBreak('row', 31)` adds a break above row 31, and `setPageBreak('row', 31, false)` removes it. The cell context menu has **Insert page break** too. Users can edit all of this in the **Page Setup** dialog, which opens with `openDialog('pageSetup')`.

## Printing

`print(options?)` or `Ctrl` + `P` renders the print area into a hidden print root, adds a print-only stylesheet that hides the rest of the page, and calls `window.print()`. The root is removed after the `afterprint` event, or when the spreadsheet is destroyed. `options.sheet` and `options.range` print another sheet or a specific range.

What prints: values with their number formats, cell styles and borders, conditional formatting fills, data bars and icons, table styles, merged cells, sparklines, pictures and charts. Hidden rows and columns are skipped. Title rows repeat on every page through a table header, and manual breaks start new pages.

## Export to PDF

`exportPdf()` writes a PDF directly, without the print dialog and without a browser. The file is vector: text is text, fills and borders are drawn shapes, and pictures are embedded. `jsonToPdf()` does the same from workbook JSON and needs no DOM, so it runs in Node, in a worker and on a server.

```ts
const bytes = await sheet.exportPdf({ sheets: 'active', title: 'Q3 budget' });
await sheet.downloadPdf('q3-budget.pdf');
```

```ts
import { writeFile } from 'node:fs/promises';
import { jsonToPdf } from '@birchui/spreadsheet';

await writeFile('register.pdf', await jsonToPdf(workbook, { sheets: ['Register'] }));
```

The pages follow the sheet's [page setup](#pages): paper size, orientation, margins, scale or fit to pages, print area, repeated title rows and columns, manual page breaks, centring, gridlines, row and column headings, headers and footers with `&P`, `&N`, `&A`, `&D`, `&T` and `&F`. Formulas are calculated first, and conditional formats, table styles and number formats are applied as on screen.

| Option | Default | Meaning |
| --- | --- | --- |
| `sheets` | `'active'` in the component, `'all'` in `jsonToPdf()` | `'all'` writes every visible sheet, `'active'` the active one, an array the named sheets in that order. |
| `range` | the print area, or the used range | An A1 range to print instead. |
| `fonts` | none | `{ regular, bold?, italic?, boldItalic? }` as the bytes of TrueType (`.ttf`) files to embed. See below. |
| `title`, `author` | the document properties | Written to the PDF's document information. |
| `fileName` | the title | The text `&F` stands for in headers and footers. |
| `date` | now | The creation date, and the date `&D` and `&T` show. Set it for reproducible files. |
| `compress` | `true` | Deflate page content and pictures. |
| `defaultColumnWidth`, `defaultRowHeight` | 88 and 22 | Sizes in pixels for columns and rows without a stored size, for `jsonToPdf()`. |
| `onReport` | none | Called with `{ pages, sheets, skipped, replacedCharacters }`. |

### Fonts

Without `fonts`, text is set in the PDF standard fonts Helvetica, Helvetica-Bold, Helvetica-Oblique and Helvetica-BoldOblique, which every PDF reader has. They cover Western European text (Windows-1252). A character outside that set is written as `?`, and `replacedCharacters` in the report counts them.

For other scripts, or to match the font on screen, pass TrueType files. The whole font file is embedded with a Unicode map, so the text can be searched and copied:

```ts
const regular = new Uint8Array(await (await fetch('/fonts/NotoSans-Regular.ttf')).arrayBuffer());
const bytes = await sheet.exportPdf({ fonts: { regular } });
```

The cell's own font name is not looked up; every cell uses the files you pass, or Helvetica. Fonts with PostScript outlines (`.otf` with CFF) and font collections (`.ttc`) are not accepted, text is laid out left to right without shaping, so Arabic, Hebrew and Indic scripts do not come out correctly, and fonts are not subset, so the PDF grows by the size of each font file.

### What is drawn

| Drawn | Not drawn |
| --- | --- |
| Cell text with bold, italic, underline, strikethrough, colour, size, alignment, indent, wrapping, rich text runs, superscript and subscript; rotated text at its angle and stacked text letter by letter | Shrink to fit is not applied; rotated text is one line and is not wrapped |
| Solid fills, the first colour of a gradient, the background of a pattern fill; data bars, solid or with their gradient, border and axis line; colour-scale fills; every icon of the twenty icon sets, drawn as a vector shape | Gradient and pattern cell fills themselves |
| All border styles including double, dashed and diagonal | |
| Merged cells; text that overflows into empty cells to the right | |
| PNG and JPEG pictures anchored to cells, and the first frame of a GIF picture with its transparency | Other picture formats, pictures placed in cells, the later frames of an animated GIF, interlaced PNG |
| [Embedded files](https://docs.birchui.com/spreadsheet/embedded-objects.md), drawn as a vector icon (page, coloured band and type badge) with the file name, or as their stored PNG or JPEG picture | The stored EMF or WMF picture of an embedded file; the icon is drawn in its place |
| Headers, footers, title rows and columns, headings, gridlines | Formatting codes in headers and footers such as `&B` or font sizes |
| The ten [chart types](https://docs.birchui.com/spreadsheet/charts.md) with title, axes, legend, data labels, trendlines and error bars; line, column and win/loss [sparklines](https://docs.birchui.com/spreadsheet/sparklines.md); [shapes](https://docs.birchui.com/spreadsheet/shapes.md) with fill, outline, dash, rotation, flip and text. All are vector drawings and their text stays text. An object that reaches across a page break is continued on the next page. | |
| [Slicers](https://docs.birchui.com/spreadsheet/slicers.md): the box, the caption and the item buttons, with the selected items filled. Items that do not fit in the height of the slicer are cut off, as the list is on screen before it is scrolled. | The clear-filter button and the scroll position of the list |

Pictures in other formats that a sheet contains are listed in `skipped` in the report, so you can tell the user. For the kitchen-sink workbook of the test suite, which has charts, shapes, sparklines, a GIF picture and two slicers, `skipped` is empty. A slicer is drawn in the colours of the light theme. Charts, sparklines and shapes are drawn from the same vector drawing the screen and the print path use; chart text is set in the PDF fonts, so line breaks in long labels can differ slightly from the screen.

The writer is checked with `qpdf --check`, by reading the text back with `pdftotext`, and by rasterising a page with `pdftoppm` and comparing it with the browser's print of the same sheet in the test suite. It writes PDF 1.7 without tags, bookmarks, links or PDF/A conformance.

### Through the browser's print pipeline

`print()` and `getPrintHtml()` produce the same pages through the browser, including charts, shapes, sparklines and slicers.

- **In the browser**, call `print()` and choose **Save as PDF** as the destination. The paper size, orientation, margins and scaling of the sheet's [page setup](#pages) are passed to the browser as `@page` rules; the browser adds its own header and footer unless the user turns them off in the dialog.
- **On a server or in a build**, pass `getPrintHtml()` to a headless browser. With Playwright:

```ts
import { chromium } from 'playwright';

const html = sheet.getPrintHtml({ title: 'Q3 budget' });
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(html);
const pdf = await page.pdf({ preferCSSPageSize: true, printBackground: true });
await browser.close();
```

`preferCSSPageSize` makes the browser use the page size in the markup, and `printBackground` keeps cell fills, data bars and table styles. `getPrintHtml()` needs a mounted spreadsheet.

## Print HTML for your own pipeline

`getPrintHtml(options?)` returns the same markup as a string, with its `@page` rules inline. It makes no network requests and works without a visible page, so you can pass it to a headless browser or an HTML-to-PDF service you already run.

```ts
const html = sheet.getPrintHtml({ range: 'A1:F40', title: 'Q3 budget' });
```

## Pages

The print output is paginated before it reaches the browser. Rows are assigned to pages from their heights, the paper size, the margins and the scale; a sheet wider than the page continues on further pages, down first and then across, as in Excel. Each page is a `<section class="lq-print-page">` with its own header, repeated title rows and footer, so `Page &P of &N` prints real numbers:

```ts
sheet.setPageSetup({
  paperSize: 'a4',
  fitToWidth: 1,
  fitToHeight: 0,
  printTitleRows: '1:1',
  header: '&LNorthwind Traders&RQ3 budget',
  footer: '&CPage &P of &N',
});
```

Manual `rowBreaks` and `columnBreaks` start a new page. When fit-to is set, manual breaks are ignored, as in Excel. [Shapes](https://docs.birchui.com/spreadsheet/shapes.md), charts and pictures print on the page that holds their anchor cell.

A row taller than its stored height, for example wrapped text in a row that was never resized, is clipped at the page edge rather than pushed to the next page.
