pdfox 0.1.0

A pure-Rust PDF library — create, parse, and render PDF documents with zero C dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/// Document builder — the top-level API for assembling a PDF.

use crate::encrypt::Encryption;
use crate::form::AcroForm;
use crate::signature::{SignatureField, SignaturePlaceholder};
use crate::watermark::{HeaderFooter, Watermark, WatermarkLayer};
use crate::object::{ObjRef, PdfDict, PdfObject, PdfStream};
use crate::outline::Outline;
use crate::page::PageBuilder;
use crate::writer::PdfWriter;

/// Hyperlink annotation: a URI link over a rectangular area on a page
pub struct LinkAnnotation {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    pub url: String,
}

impl LinkAnnotation {
    pub fn new(x: f64, y: f64, width: f64, height: f64, url: impl Into<String>) -> Self {
        Self { x, y, width, height, url: url.into() }
    }
}

/// A page with its annotations
struct BuiltPage {
    builder: PageBuilder,
    links: Vec<LinkAnnotation>,
}

/// Document-level metadata
#[derive(Default)]
pub struct DocInfo {
    pub title: Option<String>,
    pub author: Option<String>,
    pub subject: Option<String>,
    pub keywords: Option<String>,
    pub creator: String,
}

/// The top-level document builder
pub struct Document {
    pages: Vec<BuiltPage>,
    info: DocInfo,
    outline: Option<Outline>,
    form: Option<AcroForm>,
    /// Initial view: page index to open to
    initial_page: usize,
    // ── New features ──────────────────────────────────────────────────────────
    watermark: Option<Watermark>,
    header: Option<HeaderFooter>,
    footer: Option<HeaderFooter>,
    encryption: Option<Encryption>,
    signature_fields: Vec<SignatureField>,
}

impl Document {
    pub fn new() -> Self {
        Self {
            pages: Vec::new(),
            info: DocInfo { creator: "pdfox 0.1.0".into(), ..Default::default() },
            outline: None,
            form: None,
            initial_page: 0,
            watermark: None,
            header: None,
            footer: None,
            encryption: None,
            signature_fields: Vec::new(),
        }
    }

    // ── Metadata ──────────────────────────────────────────────────────────────

    pub fn title(mut self, t: impl Into<String>) -> Self {
        self.info.title = Some(t.into());
        self
    }

    pub fn author(mut self, a: impl Into<String>) -> Self {
        self.info.author = Some(a.into());
        self
    }

    pub fn subject(mut self, s: impl Into<String>) -> Self {
        self.info.subject = Some(s.into());
        self
    }

    pub fn keywords(mut self, k: impl Into<String>) -> Self {
        self.info.keywords = Some(k.into());
        self
    }

    /// Set the page that opens first (0-indexed)
    pub fn open_at(mut self, page: usize) -> Self {
        self.initial_page = page;
        self
    }

    // ── Outline (bookmarks) ───────────────────────────────────────────────────

    pub fn outline(mut self, outline: Outline) -> Self {
        self.outline = Some(outline);
        self
    }

    // ── AcroForm ──────────────────────────────────────────────────────────────

    pub fn form(mut self, form: AcroForm) -> Self {
        self.form = Some(form);
        self
    }

    // ── Pages ─────────────────────────────────────────────────────────────────

    /// Add an A4 page
    pub fn page<F>(mut self, f: F) -> Self
    where F: FnOnce(&mut PageBuilder) {
        let mut builder = PageBuilder::a4();
        f(&mut builder);
        self.pages.push(BuiltPage { builder, links: Vec::new() });
        self
    }

    /// Add a custom-size page
    pub fn page_sized<F>(mut self, width: f64, height: f64, f: F) -> Self
    where F: FnOnce(&mut PageBuilder) {
        let mut builder = PageBuilder::new(width, height);
        f(&mut builder);
        self.pages.push(BuiltPage { builder, links: Vec::new() });
        self
    }

    /// Add an A4 page with hyperlink annotations
    pub fn page_with_links<F>(mut self, f: F, links: Vec<LinkAnnotation>) -> Self
    where F: FnOnce(&mut PageBuilder) {
        let mut builder = PageBuilder::a4();
        f(&mut builder);
        self.pages.push(BuiltPage { builder, links });
        self
    }

    /// Add pre-built PageBuilders (from TextFlow or similar)
    pub fn add_pages(mut self, builders: Vec<PageBuilder>) -> Self {
        for builder in builders {
            self.pages.push(BuiltPage { builder, links: Vec::new() });
        }
        self
    }

    // ── Feature builders ─────────────────────────────────────────────────────

    /// Apply a watermark (text stamp) to every page
    pub fn watermark(mut self, w: Watermark) -> Self { self.watermark = Some(w); self }

    /// Apply a header template to every page
    pub fn header(mut self, h: HeaderFooter) -> Self { self.header = Some(h); self }

    /// Apply a footer template to every page
    pub fn footer(mut self, f: HeaderFooter) -> Self { self.footer = Some(f); self }

    /// Encrypt the document with a password
    pub fn encrypt(mut self, e: Encryption) -> Self { self.encryption = Some(e); self }

    /// Add a digital signature field. Use `build_signed()` to get the placeholder back.
    pub fn signature(mut self, s: SignatureField) -> Self {
        self.signature_fields.push(s); self
    }

    // ── Build ─────────────────────────────────────────────────────────────────

    /// Build and return the final PDF bytes.
    pub fn build(self) -> Vec<u8> {
        self.build_inner().0
    }

    /// Build and return PDF bytes + signature placeholders.
    /// After receiving the bytes you can call `placeholder.inject(pdf, pkcs7_der)`
    /// to embed the real cryptographic signature.
    pub fn build_signed(self) -> (Vec<u8>, Vec<SignaturePlaceholder>) {
        self.build_inner()
    }

    fn build_inner(self) -> (Vec<u8>, Vec<SignaturePlaceholder>) {
        let total_pages = self.pages.len();
        let mut writer = PdfWriter::new();
        writer.write_header();

        let catalog_ref = writer.reserve();
        let pages_ref   = writer.reserve();
        let info_ref    = writer.reserve();

        writer.write_object(info_ref, &PdfObject::Dictionary(self.build_info_dict()));

        let mut page_refs: Vec<ObjRef> = Vec::new();
        let mut form_widget_placement: Vec<(usize, ObjRef)> = Vec::new();

        for _ in &self.pages {
            page_refs.push(writer.reserve());
        }

        // AcroForm fields
        let mut acroform_dict: Option<PdfDict> = None;
        if let Some(ref form) = self.form {
            if !form.is_empty() {
                let (afd, placements) = form.write(&mut writer, &page_refs);
                acroform_dict = Some(afd);
                form_widget_placement = placements;
            }
        }

        // Signature fields
        let mut sig_widget_refs: Vec<(usize, ObjRef)> = Vec::new();
        let mut sig_field_refs:  Vec<ObjRef>          = Vec::new();
        let mut placeholders:    Vec<SignaturePlaceholder> = Vec::new();
        for sig in &self.signature_fields {
            let (widget_ref, field_ref, ph) = sig.write(&mut writer, &page_refs);
            let page_idx = sig.appearance.as_ref().map_or(0, |a| a.page);
            sig_widget_refs.push((page_idx, widget_ref));
            sig_field_refs.push(field_ref);
            placeholders.push(ph);
        }

        // Write each page
        for (page_idx, built_page) in self.pages.into_iter().enumerate() {
            let page_ref = page_refs[page_idx];
            let BuiltPage { builder, links } = built_page;
            let page_w = builder.width;
            let page_h = builder.height;

            let (content_bytes, images, mut resources) = builder.finish();

            // Each layer is its own compressed stream. /Contents becomes an array.
            // This prevents giant flat buffers that blow the stack on multi-page docs.
            let mut content_refs: Vec<ObjRef> = Vec::new();

            // Watermark resources (always merge even if layer=Over, to keep resource dict consistent)
            if let Some(ref wm) = self.watermark {
                let mut font_dict = match resources.get("Font") {
                    Some(PdfObject::Dictionary(d)) => d.clone(),
                    _ => PdfDict::new(),
                };
                font_dict.set("WmF1Reg", PdfObject::Dictionary(wm.font_resource()));
                resources.set("Font", PdfObject::Dictionary(font_dict));
                let mut extgs = PdfDict::new();
                extgs.set("WmGS", PdfObject::Dictionary(wm.ext_gstate()));
                resources.set("ExtGState", PdfObject::Dictionary(extgs));

                if matches!(wm.layer, WatermarkLayer::Behind) {
                    let wm_bytes = wm.render_to_stream(page_w, page_h);
                    content_refs.push(writer.add_stream(PdfStream::new_compressed(wm_bytes)));
                }
            }

            // Body content stream
            content_refs.push(writer.add_stream(PdfStream::new_compressed(content_bytes)));

            // Watermark over body
            if let Some(ref wm) = self.watermark {
                if matches!(wm.layer, WatermarkLayer::Over) {
                    let wm_bytes = wm.render_to_stream(page_w, page_h);
                    content_refs.push(writer.add_stream(PdfStream::new_compressed(wm_bytes)));
                }
            }

            // Header stream
            if let Some(ref hf) = self.header {
                let mut font_dict = match resources.get("Font") {
                    Some(PdfObject::Dictionary(d)) => d.clone(),
                    _ => PdfDict::new(),
                };
                for (key, fdict) in hf.font_resources() {
                    font_dict.set(key, PdfObject::Dictionary(fdict));
                }
                resources.set("Font", PdfObject::Dictionary(font_dict));
                let hf_bytes = hf.render(page_w, page_h, page_idx + 1, total_pages, true);
                content_refs.push(writer.add_stream(PdfStream::new_compressed(hf_bytes)));
            }

            // Footer stream
            if let Some(ref hf) = self.footer {
                let mut font_dict = match resources.get("Font") {
                    Some(PdfObject::Dictionary(d)) => d.clone(),
                    _ => PdfDict::new(),
                };
                for (key, fdict) in hf.font_resources() {
                    font_dict.set(key, PdfObject::Dictionary(fdict));
                }
                resources.set("Font", PdfObject::Dictionary(font_dict));
                let hf_bytes = hf.render(page_w, page_h, page_idx + 1, total_pages, false);
                content_refs.push(writer.add_stream(PdfStream::new_compressed(hf_bytes)));
            }

            // Image XObjects
            if !images.is_empty() {
                let mut xobj_dict = PdfDict::new();
                for (key, img) in images {
                    let img_ref = writer.add_stream(img.to_xobject_stream());
                    xobj_dict.set(key, PdfObject::Reference(img_ref));
                }
                resources.set("XObject", PdfObject::Dictionary(xobj_dict));
            }

            // Annotations
            let mut annot_refs: Vec<ObjRef> = Vec::new();
            for link in &links {
                let annot = build_link_annotation(link, page_ref);
                annot_refs.push(writer.add_object(PdfObject::Dictionary(annot)));
            }
            for &(fidx, fref) in &form_widget_placement {
                if fidx == page_idx { annot_refs.push(fref); }
            }
            for &(pidx, wref) in &sig_widget_refs {
                if pidx == page_idx { annot_refs.push(wref); }
            }

            let mut page_dict = PdfDict::new();
            page_dict.set("Type",    PdfObject::name("Page"));
            page_dict.set("Parent",  PdfObject::Reference(pages_ref));
            page_dict.set("MediaBox", PdfObject::Array(vec![
                PdfObject::Integer(0), PdfObject::Integer(0),
                PdfObject::Real(page_w), PdfObject::Real(page_h),
            ]));
            let contents_val = if content_refs.len() == 1 {
                PdfObject::Reference(content_refs[0])
            } else {
                PdfObject::Array(content_refs.iter().map(|r| PdfObject::Reference(*r)).collect())
            };
            page_dict.set("Contents", contents_val);
            page_dict.set("Resources", PdfObject::Dictionary(resources));

            if !annot_refs.is_empty() {
                let refs: Vec<PdfObject> = annot_refs.iter().map(|r| PdfObject::Reference(*r)).collect();
                page_dict.set("Annots", PdfObject::Array(refs));
            }

            writer.write_object(page_ref, &PdfObject::Dictionary(page_dict));
        }

        // /Pages
        let mut pages_dict = PdfDict::new();
        pages_dict.set("Type",  PdfObject::name("Pages"));
        pages_dict.set("Count", PdfObject::Integer(page_refs.len() as i64));
        pages_dict.set("Kids",  PdfObject::Array(
            page_refs.iter().map(|r| PdfObject::Reference(*r)).collect()
        ));
        writer.write_object(pages_ref, &PdfObject::Dictionary(pages_dict));

        // Outline
        let outline_ref = self.outline.as_ref().and_then(|o| {
            if o.is_empty() { None } else { Some(o.write(&mut writer, &page_refs)) }
        });

        // /Catalog
        let mut catalog = PdfDict::new();
        catalog.set("Type",  PdfObject::name("Catalog"));
        catalog.set("Pages", PdfObject::Reference(pages_ref));

        if let Some(oref) = outline_ref {
            catalog.set("Outlines", PdfObject::Reference(oref));
            catalog.set("PageMode", PdfObject::name("UseOutlines"));
        }

        // AcroForm — merge signature fields with form fields
        let mut all_fields: Vec<PdfObject> = Vec::new();
        if let Some(mut afd) = acroform_dict {
            if let Some(PdfObject::Array(existing)) = afd.get("Fields").cloned() {
                all_fields.extend(existing);
            }
            for &fref in &sig_field_refs {
                all_fields.push(PdfObject::Reference(fref));
            }
            afd.set("Fields", PdfObject::Array(all_fields.clone()));
            catalog.set("AcroForm", PdfObject::Dictionary(afd));
        } else if !sig_field_refs.is_empty() {
            let mut afd = PdfDict::new();
            afd.set("Fields", PdfObject::Array(
                sig_field_refs.iter().map(|r| PdfObject::Reference(*r)).collect()
            ));
            afd.set("SigFlags", PdfObject::Integer(3)); // signatures exist + append only
            catalog.set("AcroForm", PdfObject::Dictionary(afd));
        }

        if self.initial_page > 0 {
            if let Some(&dest_page) = page_refs.get(self.initial_page) {
                catalog.set("OpenAction", PdfObject::Array(vec![
                    PdfObject::Reference(dest_page),
                    PdfObject::name("Fit"),
                ]));
            }
        }

        let mut vp = PdfDict::new();
        vp.set("HideToolbar", PdfObject::Boolean(false));
        vp.set("FitWindow",   PdfObject::Boolean(true));
        catalog.set("ViewerPreferences", PdfObject::Dictionary(vp));

        writer.write_object(catalog_ref, &PdfObject::Dictionary(catalog));

        // ── Encryption ────────────────────────────────────────────────────────
        let enc_ref = self.encryption.as_ref().map(|enc| {
            // Use catalog_ref id bytes as a simple document ID
            let doc_id: Vec<u8> = (0u8..16).map(|i| i ^ (catalog_ref.id as u8)).collect();
            let enc_dict = enc.build_encrypt_dict(&doc_id);
            writer.add_object(PdfObject::Dictionary(enc_dict))
        });

        let pdf_bytes = writer.finalize_with_encrypt(catalog_ref, Some(info_ref), enc_ref);
        (pdf_bytes, placeholders)
    }

    fn build_info_dict(&self) -> PdfDict {
        let mut d = PdfDict::new();
        d.set("Creator", PdfObject::string(self.info.creator.as_str()));
        if let Some(ref t) = self.info.title    { d.set("Title",    PdfObject::string(t.as_str())); }
        if let Some(ref a) = self.info.author   { d.set("Author",   PdfObject::string(a.as_str())); }
        if let Some(ref s) = self.info.subject  { d.set("Subject",  PdfObject::string(s.as_str())); }
        if let Some(ref k) = self.info.keywords { d.set("Keywords", PdfObject::string(k.as_str())); }
        d
    }
}

fn build_link_annotation(link: &LinkAnnotation, _page_ref: ObjRef) -> PdfDict {
    let mut dict = PdfDict::new();
    dict.set("Type",    PdfObject::name("Annot"));
    dict.set("Subtype", PdfObject::name("Link"));
    dict.set("Rect", PdfObject::Array(vec![
        PdfObject::Real(link.x),
        PdfObject::Real(link.y),
        PdfObject::Real(link.x + link.width),
        PdfObject::Real(link.y + link.height),
    ]));
    dict.set("Border", PdfObject::Array(vec![
        PdfObject::Integer(0), PdfObject::Integer(0), PdfObject::Integer(0),
    ]));
    let mut action = PdfDict::new();
    action.set("Type", PdfObject::name("Action"));
    action.set("S",    PdfObject::name("URI"));
    action.set("URI",  PdfObject::string(link.url.as_str()));
    dict.set("A", PdfObject::Dictionary(action));
    dict
}