# PDF

PDF files made from parts (an invoice, a report, a ticket), read (their
pages, metadata, outline, text with where each word is, pictures, form
fields) and changed (forms filled and flattened, files merged, pages
picked, turned and stamped). All of it is `pdf`, Mote's own battery, in a
worker on the page and in place on the back end. Back to the
[map](README.md).

```mote
// docs: whole
state said = ""
state file: bytes? = none

action invoice
  let rows = [["Item", "Qty", "Price"], ["Brass gears", "3", "€36.00"], ["Punched cards", "100", "€4.50"]]
  let b = pdf.make([
    pdf.heading("Invoice 42"),
    pdf.text(["Billed to ", {text: "Ada Lovelace", bold: true}, ", 12 Analytical Row, London."]),
    pdf.table(rows, {widths: [3, 1, 1], align: ["left", "right", "right"]}),
    pdf.text("Total: €40.50", {align: "right", bold: true, size: 13}),
    pdf.text("Thank you. Payment within 30 days.", {color: "#666666"}),
  ], {title: "Invoice 42", author: "Analytical Engines Ltd", size: "A4", footer: [pdf.text("Page {page} of {pages}", {align: "center", size: 9})]})?
  file = b
  let text = pdf.read(b)?
  said = text[0]

column gap=8 padding=16
  button "Make the invoice" press=invoice disabled=pending(invoice)
  if file
    link "Open it" href=file.url("application/pdf") target="_blank"
  text said white-space=pre-wrap
  text (failure(invoice) ?? "") color=danger
```

## Mental model

A document is **a list of parts** handed to `pdf.make`, with options for
the whole file. Each part is a plain record made at once by a call that
does not wait (`pdf.text("…")`, `pdf.table(rows)`, `pdf.rect(…)`); only the
calls that make, read or change a file wait, and they can fail.

- **Parts flow or are placed.** A heading, a paragraph, a list, a table, a
  picture, a space or a rule flows down the page between the margins and
  on to new pages as it needs; give it `at: [x, y]` and it is placed there
  instead, and the flow does not move. Drawing (rectangles, lines, circles,
  paths, groups, links) is always placed.
- **Lengths are points**, 72 to the inch (a millimetre is 2.835), from the
  page's top left corner, y downwards, as on a page of the web.
- **A file is `bytes`.** Every call that reads or changes one takes its
  bytes and gives new bytes; nothing is held between calls. Pages are
  numbered from 0, like a list's items (a header's `{page}` counts from 1).
- **Fonts.** The 14 standard fonts (Helvetica, Times, Courier, each in four
  faces; Symbol; ZapfDingbats) are named, not embedded: every reader has
  them. A TrueType or OpenType file given in `fonts` is embedded, cut down
  to the glyphs used, with its kerning and ligatures, and with a map from
  its glyphs to their text, so the text copies and searches as written.

Where the work happens: Mote's own wasm (`batteries/pdf`, Rust), in the
worker pool on a page ([reactivity.md](reactivity.md#workers)) and in place
in a `server fn`. A page that uses `pdf` carries about 215 KB more (its
wasm, 420 KB, deflated and written in the page); one that uses `pdf.image`
carries the `img` battery too (about 135 KB more), which decodes a picture
that is neither a JPEG nor a plain PNG.

## Making a document

`pdf.make(parts, options)` is the file's bytes.

| Option | Means |
|---|---|
| `size` | `"A4"` (unsaid), `"A3"`, `"A5"`, `"A6"`, `"B5"`, `"letter"`, `"legal"`, `"tabloid"`, `"executive"`, or `[width, height]` in points. |
| `landscape: true` | The page turned: the longer side across. |
| `margin` | Points: one number, `[top and bottom, sides]` or `[top, right, bottom, left]`. 56 (about 2 cm) unsaid. |
| `font`, `fontSize`, `color`, `lineHeight` | What every part has unless it says: Helvetica, 11, black, 1.3. |
| `fonts` | `{Body: font, "Body Bold": fontBold}`: fonts to embed by the names parts use (what `font.open` made, or a .ttf or .otf file's bytes). |
| `header`, `footer` | Parts set on every page, in the middle of the top and the bottom margin. In their text `{page}` is the page's number and `{pages}` how many there are. |
| `title`, `author`, `subject`, `keywords`, `creator`, `lang` | What the file says of itself (a reader shows the title in its window). |
| `outline: false` | No bookmarks from the headings. |
| `trim`, `bleed` | `[x, y, width, height]`: where a printer cuts the page, and how far its pictures run past that. |

### The parts

| Part | Is |
|---|---|
| `pdf.heading(text, {level, id, bookmark})` | A heading, level 1 to 6 (bold, larger). It is a bookmark unless `bookmark: false`; with `id` a link can go to it (`link: "#id"`). It is kept with what follows it. |
| `pdf.text(text, style)` | A paragraph. `text` is a string, or a list of runs: strings and `{text, bold, italic, font, size, color, link, underline}`. A `\n` breaks the line. |
| `pdf.list(items, {ordered, start})` | Items with bullets, or numbered. |
| `pdf.table(rows, options)` | A table ([below](#tables)). |
| `pdf.image(picture, {width, height, align, at, link})` | A picture ([below](#pictures)). |
| `pdf.space(points)` | That much room. |
| `pdf.rule({color, lineWidth, space})` | A line across. |
| `pdf.pageBreak({size, landscape, margin})` | A new page, of another size if it says. |
| `pdf.rect(x, y, width, height, style)`, `pdf.line(x1, y1, x2, y2, style)`, `pdf.circle(x, y, r, style)`, `pdf.path(d, style)` | Drawing ([below](#drawing)). |
| `pdf.group(parts, {translate, rotate, scale, clip, opacity})` | Parts moved, turned, scaled, clipped or made see-through together. |
| `pdf.link(url, x, y, width, height)` | A link over a part of the page: an address, or `"#id"` (a heading's). |
| `pdf.bookmark(title, level)` | A bookmark where the flow is. |

A text's style: `font`, `size`, `bold`, `italic`, `color`, `align`
(`left`, `right`, `center`, `justify`), `lineHeight`, `link`, `underline`,
`width` (narrower than the margins), `indent`, `spaceBefore`, `spaceAfter`,
`at`, `rotate` (degrees, clockwise, about `at`), `opacity`. For text set by
a program that lays it out itself: `baseline: true` (`at` is where the
first line's baseline starts), `scaleX` and `scaleY` (1 is as the font is),
`skew` (degrees).

A colour is `"#rgb"`, `"#rrggbb"`, a name (`black`, `white`, `gray`,
`red`, `navy` …, `none`), or for print `"cmyk(0, 60, 100, 0)"` (percent),
which stays CMYK in the file.

### Text and fonts

`font: "Helvetica"`, `"Times"` and `"Courier"` (or `sans`, `serif`,
`mono`), with `bold` and `italic`, pick the standard faces; `"Symbol"` and
`"ZapfDingbats"` the two of symbols; a full name (`"Times-BoldItalic"`)
works too. Their text is in Windows' Western encoding (WinAnsi): every
character of Western European languages, curly quotes, dashes, `€`. **A
character outside it is drawn as `?`**: for Polish, Czech, Greek, Russian
and the rest, embed a font that has it.

```mote
// docs: whole
action ticket
  let body = font.open(net.bytes("/fonts/Inter.ttf")?)?
  let bold = font.open(net.bytes("/fonts/Inter-Bold.ttf")?)?
  let b = pdf.make([
    pdf.heading("Zażółć gęślą jaźń"),
    pdf.text("Ελληνικά, кириллица, and kerning: AVATAR Wave To."),
  ], {font: "Inter", fonts: {Inter: body, "Inter Bold": bold}})?
  fs.save(b, "ticket.pdf")?

button "Ticket" press=ticket
```

A part asking for `bold` in an embedded family looks for `"<name> Bold"`
(and `"<name> Italic"`, `"<name> Bold Italic"`) among `fonts`; when there
is none, the font is made bold (its outline stroked) or italic (slanted) by
hand. A glyph the font does not have is its "not found" glyph, a box.

`pdf.measure(text, {font, size, bold, italic, width, fonts})` says what
`pdf.make` would: `{width, ascent, descent, has, lines}` (in points;
`has`: whether the font has every character; `lines`, when `width` is
given: the text broken as a paragraph of that width would be, each line's
`text` and `width`). It is for a program that places text itself.

### Tables

`pdf.table(rows, options)`: `rows` is a list of rows, each a list of cells;
a cell is a text, a number, or `{text, bold, color, fill, align}`.

| Option | Means |
|---|---|
| `head: 1` | How many rows are the header (bold, filled, repeated at the top of each page the table runs on to). 1 unsaid. |
| `widths: [3, 1, 1]` | Each column's share of the width. Unsaid, by what the cells hold. |
| `align: ["left", "right"]` | Each column's alignment. |
| `width` | Narrower than the margins. |
| `lines` | `"rows"` (unsaid: a line under each row), `"grid"`, `"none"`; `border` its width (0.5), `borderColor`. |
| `headFill`, `headColor`, `stripe` | The header's fill and text colour; every other row's fill. |
| `padding`, `size`, `font`, `color`, `lineHeight` | As for text. |

A cell's text wraps; a row too tall for what is left of the page goes on
to the next.

### Pictures

`pdf.image(picture, options)`: `picture` is a file's bytes or an `image`
([media.md](media.md#mental-model)). A JPEG goes into the file as it is; a
PNG with no transparency and no interlacing as its own compressed data;
any other picture (a PNG with alpha, a GIF, a WebP, a TIFF, an `image`) is
decoded and deflated, its transparency kept as a soft mask. A picture used
twice is in the file once.

Its size: `width` and `height` in points (one of them keeps its shape);
unsaid, a pixel is three quarters of a point, and a picture wider than the
margins is made to fit them. `align` places a flowing one; `at` places it.

### Drawing

`pdf.rect`, `pdf.line`, `pdf.circle` and `pdf.path` take a style: `fill`,
`stroke`, `lineWidth`, `dash` (`[4, 2]`), `cap` (`butt`, `round`,
`square`), `join` (`miter`, `round`, `bevel`), `opacity`, `rule:
"evenodd"`, `link`, and `gradient: {colors, stops, angle, radial}` (`angle`
0 runs left to right, 90 top to bottom; `stops` where each colour is, 0 to
1). `pdf.rect` takes `radius` for round corners; `pdf.circle` takes `ry`
for an ellipse. `pdf.path` takes an SVG path (`M L H V C S Q T A Z`, and
each in lower case). With neither `fill` nor `stroke`, a shape is filled
black and a line drawn black.

```mote
// docs: whole
action badge
  let b = pdf.make([
    pdf.rect(40, 40, 200, 120, {radius: 12, gradient: {colors: ["#0a84ff", "#5e5ce6"], angle: 90}}),
    pdf.text("VISITOR", {at: [60, 70], size: 28, bold: true, color: "#ffffff"}),
    pdf.circle(200, 130, 16, {fill: "#ffffff", opacity: 0.6}),
    pdf.group([pdf.path("M 0 0 L 40 0 L 20 30 Z", {fill: "#ff9f0a"})], {translate: [60, 120], rotate: 15}),
  ], {size: [280, 200], margin: 10})?
  fs.save(b, "badge.pdf")?

button "Badge" press=badge
```

### Headers, footers, links and the outline

`header` and `footer` are parts like any other: a page number is
`pdf.text("Page {page} of {pages}", {align: "right", size: 9})`, a logo
`pdf.image(logo, {width: 60})`. Each heading is a bookmark, nested by its
level; a reader shows them beside the pages. `link: "https://…"` on a text,
a picture or a shape makes it a link; `link: "#terms"` goes to the heading
with `id: "terms"`.

## Reading a PDF

| Call | Gives |
|---|---|
| `pdf.info(b)` | `{version, pages: [{width, height, rotate}], title, author, subject, keywords, creator, producer, created, modified, outline: [{title, page, level}], form, tagged, repaired, encrypted}`. A page's size is as it is shown (turned, if it is); the dates are ISO 8601; an outline entry's `page` is -1 when it goes nowhere in the file. |
| `pdf.read(b)` | The text of each page, a line to a line. `pdf.read(b, [0, 1])` only those pages. |
| `pdf.words(b)` | `[{text, page, x, y, width, height}]`: each word and its box, in points from the page's top left as it is shown. `pdf.words(b, 0)` one page's. |
| `pdf.images(b)` | `[{page, format, width, height, place: {x, y, width, height}, data}]`: each picture a page draws, and where. `format` is `"jpeg"` (its bytes as they are in the file), `"jp2"` (JPEG 2000, as it is), `"png"` (any other, decoded and written as a PNG here), or `"ccitt"` and `"jbig2"` (fax and JBIG2 pictures, their data as it is in the file: not decoded). |
| `pdf.fields(b)` | The form's fields ([below](#forms)). |

```mote
// docs: whole
state lines: string[] = []

action open
  let f = fs.pick(".pdf")?
  if f == none return
  let info = pdf.info(f.data)?
  lines = [`${info.pages.length} pages, "${info.title}"`]
  let text = pdf.read(f.data, [0])?
  lines.push(text[0])
  for w in pdf.words(f.data, 0)?
    if w.text == "Total"
      lines.push(`"Total" is at ${w.x}, ${w.y}`)

button "Open a PDF" press=open
for l in lines
  text l
```

**What is read.** Cross-reference tables and streams, both in one file,
object streams, and every incremental update; a file whose sections are
damaged or missing is read by finding its objects (`repaired` says so).
The filters Flate, LZW, ASCII85, ASCIIHex and RunLength, with predictors.
A file encrypted by the standard handler that **opens without a password**
(one protected only against copying or printing: RC4 or AES, 40 to 256
bits) is read; one that needs a password, or that uses another handler (a
certificate's, a publisher's DRM), is refused with a sentence that says
so.

**Text** is read from each glyph's font: its map to text (ToUnicode) when it
has one; else a simple font's encoding (WinAnsi, MacRoman, Standard,
Symbol, ZapfDingbats, and the names of its Differences); else, for a font
of glyphs by number embedded as TrueType, the font file's own map, read
backwards. A ligature reads as its letters. Glyphs are joined into words
(a space, or a gap of a fifth of an em) and lines (the same baseline), in
the order the page draws them.

What comes out wrong, and why:

- **A font with no map to text** (no ToUnicode, glyph names made up, a CID
  font in one of Adobe's own CMaps such as `90ms-RKSJ-H` and no ToUnicode,
  a font program with no `cmap`): what it cannot say is `�` (U+FFFD). The
  viewer shows such text, but copies it as garbage too.
- **A scanned page** is a picture: it has no text. (Mote has no OCR.)
- **Columns** come out in the order the file draws them, which is
  usually the reading order, but not always; a table's cells come out row
  by row.
- **Text drawn as outlines** (a design tool's "outline the text") is
  drawing, not text.
- An inline picture (BI … EI) is read for `pdf.images`; a picture in a
  pattern or an annotation's look is not.

Rendering a page to pixels is not here: the browser's own viewer shows a
PDF ([below](#showing-a-pdf)).

## Forms

`pdf.fields(b)`: `[{name, kind, value, checked, options, page, x, y, width,
height, readOnly, required, multiline, multiple, maxLength}]`. `name` is the
field's full name (`"address.city"`); `kind` is `"text"`, `"check"`,
`"radio"`, `"choice"` (a combo or list box), `"button"` or `"signature"`;
`options` are a choice's options or a check box's or radio button's
states (what `fill` takes); the box is its first widget's, on its page.

`pdf.fill(b, values, {flatten})`: `values` is `{name: value}`; a text field
and a choice take a text (a choice that takes several, a list), a check
box `true` or `false` (or the name of a state), radio buttons the state to
choose. A name the form does not have, or an option a choice does not, is
refused with the ones it has.

```mote
// docs: whole
state out: bytes? = none

action sign(form: bytes)
  let fields = pdf.fields(form)?
  log(fields.map(f => `${f.name} (${f.kind})`).join(", "))
  out = pdf.fill(form, {Name: "Ada Lovelace", Agree: true, Size: "M", Colour: "Blue"}, {flatten: true})?

button "Fill" press={sign(bytes("…the form's bytes…"))}
```

A filled text field or choice gets a new look (its appearance stream),
set in the font its default appearance names when that is a simple font
whose encoding has every character, else in Helvetica; a character neither
has is drawn as `?` and the form says `NeedAppearances`, so that a viewer
that can draws the field again itself. A check box or radio button is
turned to the state asked for, whose look the form already has. A form also
described in XFA (Adobe's other form format) has that description taken
out, so every viewer shows the values. `pdf.flatten(b)`, or `{flatten:
true}`, draws each field's look into its page and takes the form away: what
was filled can no longer be changed.

## Changing a PDF

| Call | Gives |
|---|---|
| `pdf.fill(b, values, {flatten})`, `pdf.flatten(b)` | [Forms](#forms). |
| `pdf.merge([a, b, c])` | The files one after another. Their outlines follow their pages; the first file's metadata is kept; their forms' fields are put together. |
| `pdf.pages(b, [2, 0, 1])` | A new file of those pages, in that order (a page may come twice). Splitting a file is a call for each part. |
| `pdf.rotate(b, 90)`, `pdf.rotate(b, 90, [0, 2])` | Pages turned clockwise, by a multiple of 90. |
| `pdf.stamp(b, parts, {pages, under, fonts})` | Parts drawn over pages that are there (under them with `under: true`): a watermark, a signature's picture, page numbers (`{page}`, `{pages}`). Places are as the page is shown. |

Adding pages of new content is `pdf.merge([b, pdf.make(parts)?])`.

`fill`, `flatten`, `rotate` and `stamp` write an **incremental update**:
the file as it was, then what changed. It is fast, and what was there
stays as it was. `merge` and `pages` write a new file of what the pages
need. A file that had to be repaired, or that was encrypted, is written
whole and not encrypted.

```mote
// docs: whole
action draft(b: bytes)
  let marked = pdf.stamp(b, [pdf.text("DRAFT", {at: [140, 420], size: 90, color: "#cc0000", opacity: 0.15, rotate: -35})])?
  let numbered = pdf.stamp(marked, [pdf.text("{page} / {pages}", {at: [500, 800], size: 9})])?
  let first = pdf.pages(numbered, [0])?
  fs.save(pdf.merge([first, numbered])?, "draft.pdf")?

button "Draft" press={draft(bytes("…a PDF's bytes…"))}
```

## On the back end

The same calls work in a `server fn` or a route: an invoice is made where
the order is, and handed to the page as bytes or served as a file.

```mote
// docs: whole
server fn invoice(n: number): bytes
  return pdf.make([pdf.heading(`Invoice ${n}`), pdf.text("Thank you.")], {title: `Invoice ${n}`})?

server route GET "/invoice.pdf"(req)
  return {bytes: invoice(42)?, headers: {"content-type": "application/pdf"}}

link "Invoice" href="/invoice.pdf"
```

## Showing a PDF

Mote does not draw a PDF's pages. The browser has a viewer of its own: a
link to the bytes (`link "Open" href=b.url("application/pdf")
target="_blank"`) or an `iframe src=b.url("application/pdf")` shows the
file with the browser's controls (Chrome, Edge, Firefox and Safari on a
computer; a phone opens it in its own viewer, or downloads it). A preview
inside the page (a thumbnail of the first page) is made on the back end by
a program the machine has (`proc.run(["pdftoppm", …])`:
[models.md](models.md#a-picture-kept-beside-a-file)), or drawn by the
program from what `pdf.words` and `pdf.images` give.

## Pitfalls

- A character the standard fonts lack is `?`: embed a font for anything
  beyond Western European text.
- Points, not pixels: a picture with no size is its pixels × 0.75 points;
  give `width` for a photo.
- A part with `at` does not move the flow; one without it cannot be placed.
- `pdf.text` is a part (a paragraph); `pdf.read` is a file's text.
- An OpenType font with CFF outlines (a `.otf`) is embedded whole: its
  glyphs are not cut out, so the file is larger.
- The fields of merged files that share a name are two fields of one name.
- Filling an encrypted form gives a file that is not encrypted.
- Not here: digital signatures, PDF/A, tagged (accessible) structure,
  encryption when writing, a page drawn to pixels.

## Where a new call goes

A part: a field read in `batteries/pdf/layout.rs` (`Maker::part`), a
constructor in `PDP` (`runtime/shared/pdf.mote`), and its type in
`compiler/src/types/pdf.rs`. A call that waits: an op in `call`
(`batteries/pdf/core.rs`), its place in `PDF_CALLS` and `PDF`'s
arguments, its type.

## In the source

| Piece | File |
|---|---|
| The calls, their types, H270 to H275 | `compiler/src/types/pdf.rs`; emitted in `compiler/src/emit.rs` (`ns == "pdf"`) |
| The parts, the call, the driver | `runtime/shared/pdf.mote` (`PDP`, `PDF`, `PB`) |
| The battery | `batteries/pdf/`: `core.rs` (the calls), `layout.rs` (making), `fonts.rs`, `image.rs`, `write.rs`, `file.rs` (reading a file), `obj.rs`, `filter.rs`, `crypt.rs`, `read.rs` (text, pictures, metadata), `form.rs`, `edit.rs` (updates, merging); `std14.py` and `glyphs.py` make its tables |
| Its tests | `batteries/pdf/tests.rs` (`cargo test pdf::`), `tests/pdf/app.mote` (`tests/all.sh real_pdf`), `tests/fixtures/pdf/make.mjs`, `tests/fixtures/pdf/check.swift` (macOS's own reader's view of a file) |
