Change how text a page shows looks
You’ll make one word on a page bold, red and underlined. Use it to flag a changed price, restyle a heading, or match a font before you send a file on, and the words stay as they were.
The program finds the first run that says “world”, names its five glyphs and gives them a style:
// Change how text a page already shows looks: its weight, colour and underline.//// Finds the first run that says "world" and makes just that word bold, red and underlined,// leaving the rest of the run as it was. A style names runs, or glyphs inside one, and changes// only the fields it sets: a font family, a size, a colour, bold, italic, underline, raised or// lowered text, and the alignment and spacing of the run's lines. The text itself doesn't change,// so it still copies and searches as before. Bold and italic pick the face of a standard font// such as Helvetica; for another font, name the bold face as the font.import { Document } from "@laminapdf/sdk";
/** The document with "world" made bold, red and underlined on its first page. Needs `init({ extract: true })`. */export function styleText(bytes: Uint8Array): Uint8Array<ArrayBuffer> { using doc = Document.open(bytes); const found = doc.content.textRuns(0).find((r) => !r.readOnly && r.text.includes("world")); if (!found) { throw new Error('no editable run says "world"'); } // The run's glyphs are numbered from `run.start`; the word is five of them. const at = found.text.indexOf("world"); const word = { ...found.run, start: found.run.start + at, end: found.run.start + at + 5 }; doc.content.setTextStyle(0, [word], { bold: true, color: [0.8, 0, 0], underline: true }); return doc.save();}//! Change how text a page already shows looks: its weight, colour and underline.//!//! Finds the first run that says "world" and makes just that word bold, red and underlined,//! leaving the rest of the run as it was. A style names runs, or glyphs inside one, and changes//! only the fields it sets: a font family, a size, a colour, bold, italic, underline, raised or//! lowered text, and the alignment and spacing of the run's lines. The text itself doesn't change,//! so it still copies and searches as before. Bold and italic pick the face of a standard font//! such as Helvetica; for another font, name the bold face as the font.//!//! ```sh//! cargo run -p laminapdf --example style_text -- in.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{AnnotColor, Document, OpenOptions, SaveOptions, SetTextStyle, TextRunRef};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: style_text in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let styled = style(std::fs::read(input)?)?; std::fs::write(out.join("style_text.pdf"), styled)?; Ok(())}
/// The document with "world" made bold, red and underlined on its first page.pub(crate) fn style(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let runs = doc.text_runs(0)?; let found = runs .iter() .find(|r| r.read_only.is_none() && r.text.contains("world")) .ok_or("no editable run says \"world\"")?; // The run's glyphs are numbered from `run.start`; the word is five of them. let at = u32::try_from(found.text.find("world").ok_or("no \"world\"")?)?; let word = TextRunRef::new(found.run.object, found.run.start + at, found.run.start + at + 5); let mut style = SetTextStyle::new(doc.page_info(0)?.id, vec![word]); style.bold = Some(true); style.color = Some(AnnotColor::Rgb(0.8, 0.0, 0.0)); style.underline = Some(true); doc.apply(vec![style.into()])?; Ok(doc.save(&SaveOptions::new())?.bytes)}
In the result, “Hello, world!” keeps its size and position; only “world” changes, and “!” follows it.
How it works
Section titled “How it works”- A style names runs, as editing text does, or glyphs inside a run. Each field is optional and changes only what it names.
fontis"helvetica","times","courier"or the ID of a font’s bytes fromaddBlob. The run’s text is drawn again in that font as a new subset, so every character needs a glyph in it. The old font stays for the text that uses it.boldanditalicpick the face of a standard font. A font given by its bytes is one face: name the bold face as the font instead. A run whose own font has no faces to pick from (an embedded subset, a TrueType font) takesbold: trueanyway. Its glyphs are drawn filled and stroked with a thin line, unless the font’s name already says bold.- On a font with no faces,
italic: trueshears the run by 12 degrees, unless the name already says italic or oblique. A run with a text rise can’t take it.bold: falseanditalic: falseare refused on such a font, since neither can be taken off. sizeis in points.baselineraises or lowers a run at 65 % of its size.underlinedraws a line under the run as a path after the text. Lamina PDF can’t tell an underline from other lines, so it can’t take one off.alignandlineSpacingmove the lines of the run’s text object. A line aligns to the widest extent of all the object’s lines; spacing is a multiple of the glyphs’ size.- Undo: one
undo()reverts the style.
When the font lacks a character
Section titled “When the font lacks a character”An edit that needs a character the run’s font lacks fails with missing-glyph, unless you name fonts that may draw it:
const plan = doc.content.planEditText(0, run, "naïve", ["helvetica"]);// plan.substitutions: [{ text: "ï", font: "Helvetica", kind: "substitute" }]doc.content.editText(0, run, "naïve", ["helvetica"]);- A full copy of the run’s own font (its bytes, from
addBlob) adds a new subset of it. Any other font substitutes, andfidelitysays"substituted". planEditTextsays which characters and which font before you commit, so a font never changes silently. The edit’stextEditsreport the same afterwards, withgrewBy, the points the line grew by.- On a file that claims PDF/A, a font you add must be embedded: the standard 14 fonts aren’t, and the save warns with
pdfa-font-not-embedded.
Next: add text to a page, to place new text instead.