---
title: "Add text to a page"
description: "Type on an existing PDF page as page content, in any font and script, with symbols from fallback fonts, then change or remove it after saving."
version: "0.9.0"
url: "https://docs.laminapdf.com/recipes/add-text/"
---

# Add text to a page

Type on an existing PDF page as page content, in any font and script, with symbols from fallback fonts, then change or remove it after saving.

You'll type two lines on a report's first page: a note in Helvetica with one bold word, and a greeting in two scripts. You need this for an editor's text tool, a script that stamps a line on every page, or a document that has no form fields.

Unlike a text box, which is a comment, this text becomes part of the page: it prints, every reader draws it, and no one can hide it. A box in page space, points from the page's top-left corner as a viewer reports where a pointer went, says where it goes:

**TypeScript**

`packages/sdk/examples/add-text.ts`:

```ts
// Type on a page as page content: a note in Helvetica with one bold word, and a greeting in two
// scripts set in fonts given by their bytes, the second font drawing the Arabic the first lacks.
// The text becomes part of the page: it prints, every reader draws it, and it copies and searches
// as typed. The boxes are in page space (points from the page's top-left), as a viewer reports
// where a pointer went. In this tagged report each text is a paragraph that screen readers read.
// Fonts given by their bytes need the WebAssembly text module; Helvetica, Times and Courier need
// no bytes.
import { Document } from "@laminapdf/sdk";

// Where the texts go on the example's input, the quarterly report, in points from the page's
// top-left: for your own file, take them from your viewer's pointer.
/** The note: `[x0, y0, x1, y1]`. */
const NOTE = [56, 690, 300, 712] as const;
/** The greeting, under the note. */
const GREETING = [56, 718, 300, 746] as const;
/** The size of the greeting, in points. */
const GREETING_SIZE = 16;

/**
 * The document with a note and a greeting typed on its first page, saved incrementally. `at` is
 * when they were typed, as a PDF date.
 */
export function addText(bytes: Uint8Array, latin: Uint8Array, arabic: Uint8Array, at: string): Uint8Array<ArrayBuffer> {
  using doc = Document.open(bytes);

  doc.content.addText(0, {
    id: "note",
    rect: NOTE,
    runs: [{ text: "Reviewed " }, { text: "twice", bold: true }],
    fonts: ["helvetica"],
    modified: at,
  });

  // The first font draws the Latin, the second what the first lacks.
  doc.content.addText(0, {
    id: "greeting",
    rect: GREETING,
    runs: [{ text: "Hello مرحبا" }],
    fonts: [doc.addBlob(latin), doc.addBlob(arabic)],
    size: GREETING_SIZE,
    modified: at,
  });

  return doc.save({ mode: "incremental" });
}
```

**Rust**

`crates/laminapdf/examples/add_text.rs`:

````rust
//! Type on a page as page content: a note in Helvetica with one bold word, and a greeting in two
//! scripts set in fonts given by their bytes, the second font drawing the Arabic the first lacks.
//!
//! The text becomes part of the page: it prints, every reader draws it, and it copies and
//! searches as typed. The boxes are in page space (points from the page's top-left), as a viewer
//! reports where a pointer went. In this tagged report each text is a paragraph that screen
//! readers read. Fonts given by their bytes need the WebAssembly text module; Helvetica, Times
//! and Courier need no bytes.
//!
//! ```sh
//! cargo run -p laminapdf --example add_text -- in.pdf latin.ttf arabic.ttf <time> [out-dir]   # the time as a PDF date
//! ```

use std::error::Error;
use std::path::PathBuf;

use laminapdf::{
    AnnotFont, ContentId, Document, Op, OpenOptions, PdfDate, Pt, RectPt, SaveMode, SaveOptions, StandardFamily,
    TextSpan,
};

fn main() -> Result<(), Box<dyn Error>> {
    let mut args = std::env::args().skip(1);
    let usage = "usage: add_text in.pdf latin.ttf arabic.ttf <time> [out-dir]";
    let input = PathBuf::from(args.next().ok_or(usage)?);
    let latin = std::fs::read(args.next().ok_or(usage)?)?;
    let arabic = std::fs::read(args.next().ok_or(usage)?)?;
    // When the text was typed, which your app takes from its clock.
    let at: PdfDate = args.next().ok_or(usage)?.parse()?;
    let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into()));
    std::fs::create_dir_all(&out)?;
    let typed = add_text(std::fs::read(input)?, latin, arabic, at)?;
    std::fs::write(out.join("add_text.pdf"), typed)?;
    Ok(())
}

// Where the texts go on the example's input, the quarterly report, in points from the page's
// top-left: for your own file, take them from your viewer's pointer.
/// The note: `[x0, y0, x1, y1]`.
const NOTE: [f64; 4] = [56.0, 690.0, 300.0, 712.0];
/// The greeting, under the note.
const GREETING: [f64; 4] = [56.0, 718.0, 300.0, 746.0];
/// The size of the greeting, in points.
const GREETING_SIZE: f64 = 16.0;

/// The document with a note and a greeting typed on its first page, saved incrementally.
pub(crate) fn add_text(
    bytes: Vec<u8>,
    latin: Vec<u8>,
    arabic: Vec<u8>,
    at: PdfDate,
) -> Result<Vec<u8>, Box<dyn Error>> {
    let mut doc = Document::open_bytes(bytes, OpenOptions::new())?;
    let id = |name: &str| ContentId::new(name).ok_or("an ID is ASCII letters, digits, '-', '_' or '.'");

    let helvetica = AnnotFont::Standard(StandardFamily::Helvetica);
    let runs = vec![TextSpan::plain("Reviewed "), TextSpan::plain("twice").with_bold(true)];
    let note = doc
        .text_at(0, id("note")?, area(NOTE), runs, at)?
        .with_fonts(vec![helvetica], 12.0);

    // The first font draws the Latin, the second what the first lacks.
    let fonts = vec![
        AnnotFont::Font(doc.add_blob(latin)),
        AnnotFont::Font(doc.add_blob(arabic)),
    ];
    let hello = vec![TextSpan::plain("Hello \u{645}\u{631}\u{62d}\u{628}\u{627}")];
    let greeting = doc
        .text_at(0, id("greeting")?, area(GREETING), hello, at)?
        .with_fonts(fonts, GREETING_SIZE);

    doc.apply(vec![Op::from(note), Op::from(greeting)])?;
    let options = SaveOptions::new().with_mode(SaveMode::Incremental);
    Ok(doc.save(&options)?.bytes)
}

/// A box in page space from its corners.
fn area([x0, y0, x1, y1]: [f64; 4]) -> RectPt {
    RectPt::new(Pt::new(x0), Pt::new(y0), Pt::new(x1), Pt::new(y1))
}
````

**Result:** [add_text.pdf](/examples/pdf/add_text.pdf)

The result is the original bytes, unchanged, followed by one revision. The greeting's Latin letters come from the first font and the Arabic from the second, so a font you pass never has to cover every script.

## How it works

- **Fonts:** `fonts` is the font, then the fallbacks. `"helvetica"`, `"times"` and `"courier"` need no bytes and work in the extract and text modules. For any other font, add its bytes with `addBlob` and name the ID it returns. Lamina PDF embeds the part of the font the text uses, with a map that makes the text copy and search as typed.
- **Fallbacks:** each character is drawn in the first font of the chain that has it, so one list can hold a Latin font, a symbol font and the font of another script. A character no font has fails the edit with [`content-glyph-missing`](/reference/codes/content-glyph-missing.md), never a blank.
- **Layout:** the text is shaped and wrapped at the box's width, right to left where the script runs that way. It starts at the top of the box and is clipped to it, so make the box tall enough.
- **Tagging:** in a tagged file the text is a paragraph that screen readers read, or decoration they skip for `tag: "artifact"`. A file that claims PDF/UA-1 also needs every font embedded (ISO 14289-1 §7.21.4.1): text in Helvetica, Times or Courier is not, so add the font's bytes for such a file. Lamina PDF does not check this when it adds the text.
- **Finding it again:** Lamina PDF stores each text's ID and what it says with the text. After a save and a reopen, `content.added` lists it and `content.update` and `content.remove` change it.

## What to change

- **A font that forbids embedding:** a font file declares in its `OS/2` table whether it may be embedded. One that forbids it fails the edit with [`content-font-not-embeddable`](/reference/codes/content-font-not-embeddable.md); choose another font. Bytes that aren't a TrueType or OpenType font, such as a WOFF2 file, fail with [`content-font-invalid`](/reference/codes/content-font-invalid.md).
- **Size, colour and alignment:** `size` is in points, `color` a gray, RGB or CMYK array, and `align` is `"left"`, `"center"` or `"right"`.
- **Change the text later:** `content.update(index, id, { text, modified })` replaces the box, runs, fonts, size and colour, and `matrix` moves or turns it. `content.remove(index, id)` takes it off; an [incremental save](/reference/glossary.md#incremental-save) keeps the earlier revisions, and the text stays in them.
- **In the browser:** Helvetica, Times and Courier work in the extract and text modules. A font given by its bytes needs the text module: open the document after `init({ text: true })`. Elsewhere the edit fails with [`appearance-needs-text`](/reference/codes/appearance-needs-text.md).
- **A PDF/A file:** Helvetica, Times and Courier aren't embedded, which PDF/A forbids, so `doc.plan()` warns with [`pdfa-font-not-embedded`](/reference/codes/pdfa-font-not-embedded.md). Give the text a font by its bytes instead.

Next: [place images and shapes](/recipes/place-content.md) in the same way.
