pdf/lib.rs
1// pdf -- a vector PDF writer: pages of their own size drawn on a canvas (paths, fills with the
2// non-zero or even-odd rule, strokes with width, dashes, caps, joins and miter limit,
3// transforms, clipping, alpha, RGB colours, axial and radial gradients with any number of stops
4// and alpha, hatches of parallel lines), images (JPEG passed through, other pixels with
5// FlateDecode and their alpha as a soft mask), text in embedded TrueType / OpenType subsets
6// (CID fonts with Identity-H, ToUnicode for search and copy, glyphs and widths from the
7// library's shaping), links to URIs and to places in the document, nested outlines
8// (bookmarks), the document information and XMP metadata, form fields (form.rs), encryption with
9// AES-256 or AES-128 (encrypt.rs). PDF 1.7 with a classic xref table; the same document with the
10// same options always gives the same bytes (an encrypted one with the same Encryption::with_seed). Not here: PDF/A. And a
11// reader, pdf::read: structure, encryption, text, outlines, forms, attachments, and drawing pages
12// (below); pdf::edit changes what it read and saves it as an incremental update (forms filled in
13// and flattened) or writes it again in full (encrypted, decrypted, with another password).
14//
15// let mut doc = Document::new();
16// let page = doc.add_page(A4.0, A4.1); // points (1/72 inch); mm(210.0) converts
17// let font = doc.add_font(bytes, 0)?; // TrueType / OpenType (CFF), a collection's face
18// {
19// let mut c = doc.canvas(page, Origin::TopLeft); // or BottomLeft (PDF's own page space)
20// c.set_fill_color(Rgb::hex(0x2060C0));
21// c.rect(40.0, 40.0, 200.0, 100.0);
22// c.fill(FillRule::NonZero);
23// c.text(font, 12.0, 40.0, 180.0, "Hallo, Welt"); // shaped; returns the advance
24// c.link_uri(40.0, 168.0, 80.0, 16.0, "https://example.org/");
25// } // the drawing goes into the page here
26// doc.add_outline(None, "Start", Dest::Fit(page));
27// let bytes = doc.write()?;
28//
29// Document add_page / page_size / page_count, canvas(page, origin) -> Canvas,
30// add_font -> FontId, font_metrics, shape, text_width, add_image(Image) -> ImageId,
31// add_outline -> OutlineId, set_outline_open, set_info(Info), set_language,
32// set_compression, set_encryption(Some(Encryption)), write() -> bytes
33// Encryption aes256 / aes128(user, owner), permissions(Permissions), encrypt_metadata,
34// with_seed; Permissions PRINT, MODIFY, COPY, ANNOTATE, FILL_FORMS, ...
35// Canvas save / restore, transform / translate / scale / rotate, fill / stroke colour and
36// alpha, line width, cap, join, miter limit, dash, path building (move_to,
37// line_to, curve_to, quad_to, rect, rounded_rect, ellipse, circle, arc, close,
38// append_path), fill / stroke / fill_stroke / clip / end_path, shade /
39// fill_shading (gradients), fill_hatch, image / image_transform, text /
40// text_fallback / glyphs, set_text_mode, link_uri / link_dest, dest (a
41// destination at a point of this canvas), text_field / check_box / radio /
42// combo_box / list_box / push_button / signature_field (TextField, FieldStyle,
43// FieldFont, Align)
44// Path the same path building, kept and drawn later (Canvas::fill_path, stroke_path)
45// Shading a gradient: ShadingKind Axial / Radial (PDF shading types 2 and 3), stops
46// (t, colour, alpha), extend; Shading::axial / radial
47// Hatch parallel lines: angle, spacing, width, colour, alpha, a point on a line
48// Image jpeg(file), gray / rgb / rgba(w, h, pixels), from_surface(gfx::Surface),
49// with_alpha, interpolate
50//
51// Text: Canvas::text shapes one line with lib/text_shape (HarfRust: kerning, ligatures, marks,
52// Arabic joining, bidi); Canvas::glyphs takes glyphs a layout shaped already (pdf::Glyph). Each glyph is
53// placed where the shaping put it (TJ adjustments against the font's widths); the CIDs are the
54// font's glyph ids. The first glyph of each cluster maps to the cluster's text in ToUnicode.
55// Variable fonts are embedded at their default instance, colour glyphs as their outlines.
56// Fonts whose OS/2 fsType forbids embedding are refused (Error::FontLicense); fsType "no
57// subsetting" embeds every glyph.
58//
59// Gradients (shading.rs): DeviceRGB shadings with a Type 2 function per stretch between stops,
60// stitched by a Type 3 function; one alpha for all stops is the fill alpha (ExtGState ca), varying
61// alpha a luminosity soft mask (a transparency group painting the alphas as a DeviceGray shading
62// in the same user space). Degenerate gradients paint the last stop's colour as SVG does.
63// Hatches are clipped, stroked lines in one path, not tiling patterns (pdfium shows seams between
64// rotated pattern cells, and readers round the cell step to device pixels).
65//
66// Reading: pdf::read (read/mod.rs) opens PDF files of every version, also encrypted and damaged
67// ones, and gives their objects, pages, text with the position of every glyph, information,
68// outlines, links and other annotations, form fields, attachments and page labels. It shares
69// Info and Date with the writer and nothing else.
70#![no_std]
71#![forbid(unsafe_code)]
72
73extern crate alloc;
74
75mod appear;
76mod canvas;
77mod cff;
78pub mod edit;
79mod encrypt;
80mod font;
81mod form;
82mod geom;
83mod image;
84mod obj;
85pub mod read;
86mod shading;
87mod write;
88
89use alloc::collections::{BTreeMap, BTreeSet};
90use alloc::string::String;
91use alloc::vec::Vec;
92
93pub use canvas::{Canvas, Origin};
94pub use encrypt::{Cipher, Encryption, Permissions};
95pub use font::FontMetrics;
96pub use form::{Align, FieldFont, FieldStyle, TextField};
97pub use geom::{FillRule, LineCap, LineJoin, Matrix, Path, Rgb, TextMode};
98pub use image::Image;
99pub use shading::{Hatch, Shading, ShadingKind};
100
101/// A4 portrait in points
102pub const A4: (f64, f64) = (595.275_590_551_181_1, 841.889_763_779_527_6);
103/// A3 portrait in points
104pub const A3: (f64, f64) = (841.889_763_779_527_6, 1_190.551_181_102_362_2);
105/// A5 portrait in points
106pub const A5: (f64, f64) = (419.527_559_055_118_1, 595.275_590_551_181_1);
107/// US Letter portrait in points
108pub const LETTER: (f64, f64) = (612.0, 792.0);
109/// US Legal portrait in points
110pub const LEGAL: (f64, f64) = (612.0, 1008.0);
111
112/// millimetres in points
113pub fn mm(v: f64) -> f64 {
114 v * 72.0 / 25.4
115}
116
117/// inches in points
118pub fn inch(v: f64) -> f64 {
119 v * 72.0
120}
121
122/// the smallest and largest page side PDF readers take (ISO 32000-1, Annex C)
123pub const PAGE_MIN: f64 = 3.0;
124pub const PAGE_MAX: f64 = 14_400.0;
125
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub enum Error {
128 /// the font file cannot be used: damaged, or a kind not taken
129 Font(&'static str),
130 /// the font's licence (OS/2 fsType) does not allow embedding
131 FontLicense(&'static str),
132 /// image data that does not fit what it claims
133 Image(&'static str),
134 /// valid input this writer does not handle (CFF2 fonts, arithmetic-coded JPEG, ...)
135 Unsupported(&'static str),
136 /// the document cannot be written as it is (no pages, a link to a page it lacks, ...)
137 Invalid(&'static str),
138}
139
140impl core::fmt::Display for Error {
141 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
142 match self {
143 Error::Font(s) => write!(f, "font: {s}"),
144 Error::FontLicense(s) => write!(f, "font licence: {s}"),
145 Error::Image(s) => write!(f, "image: {s}"),
146 Error::Unsupported(s) => write!(f, "not supported: {s}"),
147 Error::Invalid(s) => write!(f, "invalid document: {s}"),
148 }
149 }
150}
151
152impl core::error::Error for Error {}
153
154/// a shaped glyph for Canvas::glyphs: Document::shape gives them, a text layout that shaped
155/// its lines already builds its own
156#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
157pub struct Glyph {
158 /// which of the fonts passed along (0: the first)
159 pub font: usize,
160 /// the glyph id in that font
161 pub id: u32,
162 /// how far the pen moves after the glyph, in font units
163 pub advance: i32,
164 /// the glyph's offset from the pen in font units (y up)
165 pub x: i32,
166 pub y: i32,
167 /// the byte range of the text the glyph stands for (its cluster): cluster..end
168 pub cluster: usize,
169 pub end: usize,
170}
171
172/// a page of a document (Document::add_page), counted from 0
173#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
174pub struct PageId(pub u32);
175
176/// a font of a document (Document::add_font)
177#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
178pub struct FontId(u32);
179
180/// an image of a document (Document::add_image)
181#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
182pub struct ImageId(u32);
183
184/// an outline item (Document::add_outline)
185#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
186pub struct OutlineId(u32);
187
188/// a place in the document for links and outline items
189#[derive(Clone, Copy, Debug, PartialEq)]
190pub enum Dest {
191 /// the whole page in the window
192 Fit(PageId),
193 /// the point (left, top) of PDF page space (points from the bottom left, y up) at the top
194 /// left of the window; zoom None keeps the reader's (Canvas::dest builds one from a
195 /// canvas's own coordinates)
196 Xyz { page: PageId, left: f64, top: f64, zoom: Option<f64> },
197}
198
199impl Dest {
200 fn page(&self) -> PageId {
201 match *self {
202 Dest::Fit(p) | Dest::Xyz { page: p, .. } => p,
203 }
204 }
205}
206
207/// a date of the document information: local time and its offset from UTC
208#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
209pub struct Date {
210 pub year: u16,
211 pub month: u8,
212 pub day: u8,
213 pub hour: u8,
214 pub minute: u8,
215 pub second: u8,
216 /// minutes east of UTC (+60: Central European Time), -1439 to 1439
217 pub offset_minutes: i16,
218}
219
220/// the document information (the Info dictionary and the same in XMP metadata); unset fields
221/// are left out
222#[derive(Clone, Debug, Default, PartialEq)]
223pub struct Info {
224 pub title: Option<String>,
225 pub author: Option<String>,
226 pub subject: Option<String>,
227 pub keywords: Option<String>,
228 /// the program the document was made with
229 pub creator: Option<String>,
230 /// the program that wrote the PDF (None: "JFLib")
231 pub producer: Option<String>,
232 pub created: Option<Date>,
233 pub modified: Option<Date>,
234}
235
236#[derive(Clone, Debug)]
237pub(crate) enum LinkTarget {
238 Uri(String),
239 Dest(Dest),
240}
241
242#[derive(Clone, Debug)]
243pub(crate) struct Link {
244 /// x0, y0, x1, y1 in page space
245 pub(crate) rect: [f64; 4],
246 pub(crate) target: LinkTarget,
247}
248
249pub(crate) struct PageData {
250 pub(crate) width: f64,
251 pub(crate) height: f64,
252 pub(crate) content: Vec<u8>,
253 pub(crate) fonts: BTreeSet<usize>,
254 pub(crate) images: BTreeSet<usize>,
255 pub(crate) gstates: BTreeSet<usize>,
256 pub(crate) shadings: BTreeSet<usize>,
257 pub(crate) masks: BTreeSet<usize>,
258 pub(crate) links: Vec<Link>,
259 pub(crate) transparency: bool,
260}
261
262pub(crate) struct OutlineItem {
263 pub(crate) title: String,
264 pub(crate) dest: Dest,
265 pub(crate) parent: Option<usize>,
266 pub(crate) open: bool,
267}
268
269/// a PDF document being built: its pages, fonts, images, outlines and information
270pub struct Document {
271 pub(crate) pages: Vec<PageData>,
272 pub(crate) fonts: Vec<font::FontData>,
273 pub(crate) images: Vec<Image>,
274 /// ExtGState table: (fill alpha, stroke alpha) in thousandths
275 pub(crate) alphas: Vec<(u16, u16)>,
276 pub(crate) alpha_ids: BTreeMap<(u16, u16), usize>,
277 /// shading dictionaries (without << >>), each written once
278 pub(crate) shadings: Vec<Vec<u8>>,
279 pub(crate) shading_ids: BTreeMap<Vec<u8>, usize>,
280 /// soft masks: the DeviceGray shading their group paints and the group's /BBox
281 pub(crate) masks: Vec<(usize, [f64; 4])>,
282 pub(crate) mask_ids: BTreeMap<(usize, Vec<u8>), usize>,
283 pub(crate) outlines: Vec<OutlineItem>,
284 pub(crate) info: Info,
285 pub(crate) lang: Option<String>,
286 pub(crate) level: u8,
287 /// the fields of the interactive form (form.rs), by full name
288 pub(crate) fields: Vec<form::FieldData>,
289 pub(crate) field_ids: BTreeMap<String, usize>,
290 /// why write() fails for the form: two fields of one name, ...
291 pub(crate) form_error: Option<&'static str>,
292 pub(crate) encryption: Option<Encryption>,
293}
294
295impl Default for Document {
296 fn default() -> Document {
297 Document::new()
298 }
299}
300
301impl Document {
302 pub fn new() -> Document {
303 Document {
304 pages: Vec::new(),
305 fonts: Vec::new(),
306 images: Vec::new(),
307 alphas: Vec::new(),
308 alpha_ids: BTreeMap::new(),
309 shadings: Vec::new(),
310 shading_ids: BTreeMap::new(),
311 masks: Vec::new(),
312 mask_ids: BTreeMap::new(),
313 outlines: Vec::new(),
314 info: Info::default(),
315 lang: None,
316 level: 6,
317 fields: Vec::new(),
318 field_ids: BTreeMap::new(),
319 form_error: None,
320 encryption: None,
321 }
322 }
323
324 /// a new page at the end, width and height in points (clamped to PAGE_MIN .. PAGE_MAX)
325 pub fn add_page(&mut self, width: f64, height: f64) -> PageId {
326 let side = |v: f64| if v.is_finite() { v.clamp(PAGE_MIN, PAGE_MAX) } else { A4.0 };
327 self.pages.push(PageData {
328 width: side(width),
329 height: side(height),
330 content: Vec::new(),
331 fonts: BTreeSet::new(),
332 images: BTreeSet::new(),
333 gstates: BTreeSet::new(),
334 shadings: BTreeSet::new(),
335 masks: BTreeSet::new(),
336 links: Vec::new(),
337 transparency: false,
338 });
339 PageId(self.pages.len() as u32 - 1)
340 }
341
342 pub fn page_count(&self) -> usize {
343 self.pages.len()
344 }
345
346 /// width and height in points
347 pub fn page_size(&self, page: PageId) -> Option<(f64, f64)> {
348 self.pages.get(page.0 as usize).map(|p| (p.width, p.height))
349 }
350
351 /// drawing on a page (panics for a page this document does not have)
352 pub fn canvas(&mut self, page: PageId, origin: Origin) -> Canvas<'_> {
353 assert!((page.0 as usize) < self.pages.len(), "pdf: no page {}", page.0);
354 Canvas::new(self, page.0 as usize, origin)
355 }
356
357 /// a TrueType or OpenType font (glyf or CFF outlines; `face`: of a collection, else 0)
358 pub fn add_font(&mut self, data: Vec<u8>, face: u32) -> Result<FontId, Error> {
359 let f = font::FontData::parse(data, face)?;
360 self.fonts.push(f);
361 Ok(FontId(self.fonts.len() as u32 - 1))
362 }
363
364 pub fn font_metrics(&self, font: FontId) -> Option<FontMetrics> {
365 self.fonts.get(font.0 as usize).map(|f| f.metrics)
366 }
367
368 /// one line shaped with the fonts (the first, then fallbacks per script run); empty for an
369 /// unknown font or a line beyond 64 KiB
370 pub fn shape(&self, fonts: &[FontId], text: &str) -> Vec<Glyph> {
371 let Some(first) = fonts.first().and_then(|f| self.fonts.get(f.0 as usize)) else { return Vec::new() };
372 let mut rest = Vec::new();
373 for f in &fonts[1..] {
374 match self.fonts.get(f.0 as usize) {
375 Some(fd) => rest.push(&fd.engine),
376 None => return Vec::new(),
377 }
378 }
379 let glyphs = first.engine.shape_with_fallback(text, &rest).unwrap_or_default();
380 glyphs.iter().map(|g| Glyph { font: g.font, id: g.id, advance: g.advance, x: g.x, y: g.y, cluster: g.cluster, end: g.end }).collect()
381 }
382
383 /// the advance of one shaped line at `size` points
384 pub fn text_width(&self, fonts: &[FontId], size: f64, text: &str) -> f64 {
385 let mut w = 0.0;
386 for g in self.shape(fonts, text) {
387 if let Some(f) = fonts.get(g.font).and_then(|f| self.fonts.get(f.0 as usize)) {
388 w += g.advance as f64 * size / f.upem as f64;
389 }
390 }
391 w
392 }
393
394 pub fn add_image(&mut self, img: Image) -> ImageId {
395 self.images.push(img);
396 ImageId(self.images.len() as u32 - 1)
397 }
398
399 /// an outline item (bookmark) under `parent` (None: at the top), after its siblings; open
400 /// (its children shown) until set_outline_open says otherwise
401 pub fn add_outline(&mut self, parent: Option<OutlineId>, title: &str, dest: Dest) -> OutlineId {
402 let parent = parent.map(|p| p.0 as usize).filter(|&p| p < self.outlines.len());
403 self.outlines.push(OutlineItem { title: String::from(title), dest, parent, open: true });
404 OutlineId(self.outlines.len() as u32 - 1)
405 }
406
407 pub fn set_outline_open(&mut self, item: OutlineId, open: bool) {
408 if let Some(o) = self.outlines.get_mut(item.0 as usize) {
409 o.open = open;
410 }
411 }
412
413 pub fn set_info(&mut self, info: Info) {
414 self.info = info;
415 }
416
417 /// the document's language (BCP 47, e.g. "de-DE")
418 pub fn set_language(&mut self, lang: &str) {
419 self.lang = Some(String::from(lang));
420 }
421
422 /// DEFLATE level 0 (streams uncompressed, for reading the file) to 9; default 6
423 pub fn set_compression(&mut self, level: u8) {
424 self.level = level.min(9);
425 }
426
427 /// encrypt the file (None: not, the default); see Encryption
428 pub fn set_encryption(&mut self, e: Option<Encryption>) {
429 self.encryption = e;
430 }
431
432 /// the PDF file
433 pub fn write(&self) -> Result<Vec<u8>, Error> {
434 write::write(self)
435 }
436
437 /// a shading dictionary's index (the same dictionary twice: one object)
438 pub(crate) fn add_shading(&mut self, dict: Vec<u8>) -> usize {
439 let next = self.shadings.len();
440 let i = *self.shading_ids.entry(dict.clone()).or_insert(next);
441 if i == next {
442 self.shadings.push(dict);
443 }
444 i
445 }
446
447 /// a soft mask's index: the group painting gray shading g over bbox
448 pub(crate) fn add_mask(&mut self, g: usize, bbox: [f64; 4]) -> usize {
449 let mut key = Vec::new();
450 obj::nums(&mut key, &bbox);
451 let next = self.masks.len();
452 let i = *self.mask_ids.entry((g, key)).or_insert(next);
453 if i == next {
454 self.masks.push((g, bbox));
455 }
456 i
457 }
458}