lightweight-pdf-core 0.3.0

Document model, elements and builder API for lightweight-pdf
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use crate::element::Element;
use std::rc::Rc;

/// Page formats supported for documents. Dimensions in PDF points (1/72 inch).
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum PageFormat {
    A3,
    A4,
    A5,
    Letter,
    Legal,
    Custom(f32, f32),
}

impl PageFormat {
    /// (width, height) in points, portrait.
    pub fn size(&self) -> (f32, f32) {
        match self {
            PageFormat::A3 => (841.8898, 1190.5512),
            PageFormat::A4 => (595.2756, 841.8898),
            PageFormat::A5 => (419.5276, 595.2756),
            PageFormat::Letter => (612.0, 792.0),
            PageFormat::Legal => (612.0, 1008.0),
            PageFormat::Custom(w, h) => (*w, *h),
        }
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "snake_case"))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Orientation {
    #[default]
    Portrait,
    Landscape,
}

#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(deny_unknown_fields, default)
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default)]
pub struct DocumentMetadata {
    pub title: Option<String>,
    pub author: Option<String>,
    pub subject: Option<String>,
    pub keywords: Option<String>,
    pub creator: Option<String>,
    pub creation_date: Option<PdfDate>,
    pub mod_date: Option<PdfDate>,
}

/// A UTC timestamp for `/CreationDate`/`/ModDate`. Always an explicit
/// caller-supplied value, never read from the system clock: `wasm32-unknown-unknown`
/// has none, and reproducible output (same `Document` -> byte-identical
/// PDF) is a feature, not an accident.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(deny_unknown_fields))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct PdfDate {
    pub year: u16,
    pub month: u8,
    pub day: u8,
    pub hour: u8,
    pub minute: u8,
    pub second: u8,
}

impl PdfDate {
    pub fn new(year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> Self {
        PdfDate {
            year,
            month,
            day,
            hour,
            minute,
            second,
        }
    }

    /// `D:YYYYMMDDHHmmSSZ` — the PDF date string format (ISO/IEC 32000-1
    /// 7.9.4), UTC only (no offset support needed here).
    pub fn to_pdf_string(self) -> String {
        format!(
            "D:{:04}{:02}{:02}{:02}{:02}{:02}Z",
            self.year, self.month, self.day, self.hour, self.minute, self.second
        )
    }

    /// ISO 8601, as XMP (`xmp:CreateDate`/`xmp:ModifyDate`) wants it — the
    /// same fields as `to_pdf_string`, just reordered/repunctuated, not a
    /// second date representation (issue #25).
    pub fn to_xmp_string(self) -> String {
        format!(
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
            self.year, self.month, self.day, self.hour, self.minute, self.second
        )
    }
}

#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(deny_unknown_fields, default)
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Clone, Copy, PartialEq, Debug, Default)]
pub struct Margin {
    pub top: f32,
    pub right: f32,
    pub bottom: f32,
    pub left: f32,
}

impl Margin {
    pub fn symmetric(horizontal: f32, vertical: f32) -> Self {
        Margin {
            top: vertical,
            right: horizontal,
            bottom: vertical,
            left: horizontal,
        }
    }

    pub fn all(value: f32) -> Self {
        Margin {
            top: value,
            right: value,
            bottom: value,
            left: value,
        }
    }
}

/// Passed to `Header`/`Footer` closures on every (re-)evaluation. Plain data
/// only, so it can live in `lightweight-pdf-core` without pulling in layout/font
/// knowledge (ADR-010).
#[derive(Clone, Copy, Debug)]
pub struct PageContext {
    pub page: usize,
    pub total_pages: usize,
}

type HeaderFooterFn = Rc<dyn Fn(&PageContext) -> Element>;

/// A header band with a fixed, document-creation-time height (ADR-011): the
/// closure may vary its content per page but never the reserved band size.
#[derive(Clone)]
pub struct Header {
    pub height: f32,
    pub content: HeaderFooterFn,
}

impl Header {
    pub fn new(height: f32, content: impl Fn(&PageContext) -> Element + 'static) -> Self {
        Header {
            height,
            content: Rc::new(content),
        }
    }
}

#[derive(Clone)]
pub struct Footer {
    pub height: f32,
    pub content: HeaderFooterFn,
}

impl Footer {
    pub fn new(height: f32, content: impl Fn(&PageContext) -> Element + 'static) -> Self {
        Footer {
            height,
            content: Rc::new(content),
        }
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(deny_unknown_fields))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Clone)]
pub struct Document {
    pub page_format: PageFormat,
    #[cfg_attr(feature = "serde", serde(default))]
    pub orientation: Orientation,
    #[cfg_attr(feature = "serde", serde(default))]
    pub margin: Margin,
    /// Not representable in the JSON schema (issue #17 V1 scope): the
    /// content is a Rust closure, re-evaluated per page. Always `None` on
    /// a JSON-loaded `Document`; `Document::to_json` refuses to serialize
    /// a `Document` that has one set rather than silently dropping it.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub header: Option<Header>,
    #[cfg_attr(feature = "serde", serde(skip))]
    pub footer: Option<Footer>,
    #[cfg_attr(feature = "serde", serde(skip, default = "default_visible_from"))]
    pub header_visible_from: usize,
    #[cfg_attr(feature = "serde", serde(skip, default = "default_visible_from"))]
    pub footer_visible_from: usize,
    #[cfg_attr(feature = "serde", serde(default))]
    pub watermark: Option<crate::watermark::Watermark>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub metadata: DocumentMetadata,
    /// `None` (the default) means every element renders exactly as it
    /// always did — `Document::theme(..)` opts in per-document, resolved
    /// once per element as it's `.add()`-ed (see `theme::apply_theme`).
    #[cfg_attr(feature = "serde", serde(default))]
    pub theme: Option<crate::theme::Theme>,
    /// Set by `.pdf_a3b()` (issue #25): asks the facade to write a
    /// PDF/A-3b-conformant document (XMP metadata, `/OutputIntent` with an
    /// embedded sRGB ICC profile, transparency-group colour space) instead
    /// of the default output. Always present on `Document` regardless of
    /// the facade's `pdf-a` Cargo feature (this flag itself costs
    /// nothing) — `render()` returns `RenderError::PdfAFeatureDisabled` if
    /// this is `true` but that feature isn't compiled in, rather than
    /// silently rendering a non-conformant PDF.
    #[cfg_attr(feature = "serde", serde(default))]
    pub pdf_a3b: bool,
    /// Set by `.zugferd_xml(bytes)` (issue #26): the raw bytes of a
    /// caller-supplied ZUGFeRD/Factur-X invoice XML (EN 16931/Comfort
    /// profile) to embed as an associated file. This crate embeds only —
    /// it never generates or validates that XML itself (see ADR-018 in
    /// the local `plan/00-decisions.md`). Not representable in the JSON
    /// schema (same reasoning as `Header`/`Footer`: `to_json()` refuses
    /// outright rather than silently dropping it).
    #[cfg_attr(feature = "serde", serde(skip))]
    pub zugferd_xml: Option<Vec<u8>>,
    /// Set by `.pdf_ua()` (issue #27): asks the facade to write a Tagged
    /// PDF/PDF-UA-conformant document — a structure tree (`/StructTreeRoot`,
    /// one `/StructElem` per heading/paragraph/table/list/figure),
    /// marked content (`BDC`/`EMC` with MCIDs) in every content stream,
    /// and watermark/header/footer content marked as artifacts rather
    /// than structure. Always present regardless of the facade's
    /// `tagged-pdf` Cargo feature (this flag costs nothing) —
    /// `render()` returns `RenderError::TaggedPdfFeatureDisabled` if this
    /// is `true` but that feature isn't compiled in.
    #[cfg_attr(feature = "serde", serde(default))]
    pub pdf_ua: bool,
    /// Document natural language (e.g. `"en-US"`, `"de-DE"`) for the
    /// Catalog's `/Lang` entry — required for PDF/UA, meaningful even
    /// without it (screen readers use `/Lang` to pick a voice/language).
    #[cfg_attr(feature = "serde", serde(default))]
    pub lang: Option<String>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub children: Vec<Element>,
}

#[cfg(feature = "serde")]
fn default_visible_from() -> usize {
    1
}

impl Document {
    pub fn new(page_format: PageFormat) -> Self {
        Document {
            page_format,
            orientation: Orientation::default(),
            margin: Margin::default(),
            header: None,
            footer: None,
            header_visible_from: 1,
            footer_visible_from: 1,
            watermark: None,
            metadata: DocumentMetadata::default(),
            theme: None,
            pdf_a3b: false,
            zugferd_xml: None,
            pdf_ua: false,
            lang: None,
            children: Vec::new(),
        }
    }

    pub fn theme(mut self, theme: crate::theme::Theme) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Opt in to PDF/A-3b-conformant output (issue #25) — see
    /// `Document::pdf_a3b`'s field doc comment. Needs the facade's `pdf-a`
    /// Cargo feature; without it, `render()` returns
    /// `RenderError::PdfAFeatureDisabled` rather than silently ignoring
    /// this.
    pub fn pdf_a3b(mut self) -> Self {
        self.pdf_a3b = true;
        self
    }

    /// Embeds `xml` as the document's ZUGFeRD/Factur-X invoice data
    /// (EN 16931/Comfort profile, issue #26) — implies `.pdf_a3b()`
    /// (ZUGFeRD/Factur-X *is* a PDF/A-3 file with an embedded invoice,
    /// not an independent opt-in). `xml` must already be a valid EN
    /// 16931 CrossIndustryInvoice document; this crate embeds it
    /// byte-for-byte and never generates or validates the XML itself
    /// (ADR-018).
    pub fn zugferd_xml(mut self, xml: impl Into<Vec<u8>>) -> Self {
        self.pdf_a3b = true;
        self.zugferd_xml = Some(xml.into());
        self
    }

    /// Opt in to Tagged PDF/PDF-UA output (issue #27) — see
    /// `Document::pdf_ua`'s field doc comment. Implies `.pdf_a3b()`: both
    /// need the same XMP/`OutputIntent` machinery, and a combined
    /// PDF/A+PDF/UA document (archival *and* accessible) is what most
    /// real producers of this document class actually want — PDF/UA
    /// without PDF/A isn't a supported combination (ADR-019 in the local
    /// `plan/00-decisions.md`). Needs the facade's `tagged-pdf` Cargo
    /// feature; without it, `render()` returns
    /// `RenderError::TaggedPdfFeatureDisabled`.
    pub fn pdf_ua(mut self) -> Self {
        self.pdf_a3b = true;
        self.pdf_ua = true;
        self
    }

    /// Sets the Catalog's `/Lang` (e.g. `"en-US"`).
    pub fn lang(mut self, lang: impl Into<String>) -> Self {
        self.lang = Some(lang.into());
        self
    }

    /// Effective page dimensions (width, height) in PDF points, accounting for orientation.
    pub fn page_size(&self) -> (f32, f32) {
        let (w, h) = self.page_format.size();
        match self.orientation {
            Orientation::Portrait => (w, h),
            Orientation::Landscape => (h, w),
        }
    }

    pub fn orientation(mut self, orientation: Orientation) -> Self {
        self.orientation = orientation;
        self
    }

    pub fn landscape(mut self) -> Self {
        self.orientation = Orientation::Landscape;
        self
    }

    pub fn portrait(mut self) -> Self {
        self.orientation = Orientation::Portrait;
        self
    }

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

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

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

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

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

    pub fn creation_date(mut self, date: PdfDate) -> Self {
        self.metadata.creation_date = Some(date);
        self
    }

    pub fn mod_date(mut self, date: PdfDate) -> Self {
        self.metadata.mod_date = Some(date);
        self
    }

    pub fn margin(mut self, margin: Margin) -> Self {
        self.margin = margin;
        self
    }

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

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

    /// First page number (1-based) on which the header is drawn. Cover-page
    /// convenience, see `plan/02-elementcatalog-and-features.md` ("Deckblatt
    /// / Titelseite").
    pub fn header_visible_from(mut self, page: usize) -> Self {
        self.header_visible_from = page;
        self
    }

    pub fn footer_visible_from(mut self, page: usize) -> Self {
        self.footer_visible_from = page;
        self
    }

    /// Sets a document-wide diagonal stamp ("ENTWURF", "STORNIERT") — an
    /// independent layer, not a normal flow element (Phase 6).
    pub fn watermark(mut self, watermark: crate::watermark::Watermark) -> Self {
        self.watermark = Some(watermark);
        self
    }

    pub fn add(&mut self, element: impl Into<Element>) -> &mut Self {
        let mut element = element.into();
        if let Some(theme) = &self.theme {
            crate::theme::apply_theme(&mut element, theme);
        }
        self.children.push(element);
        self
    }
}

// ---------------------------------------------------------------------
// JSON (issue #17): `Document` ↔ JSON, behind the `serde` feature.
// Header/Footer aren't representable (Rust closures) — excluded from the
// wire format entirely rather than silently dropped; `to_json` refuses
// outright if either is set.
// ---------------------------------------------------------------------

#[cfg(feature = "serde")]
pub const CURRENT_SCHEMA_VERSION: u32 = 1;

/// The versioned envelope every JSON document is wrapped in (ADR-009: an
/// external entry point needs a schema version from day one to stay
/// extensible). Deliberately not `#[serde(flatten)]`ed into `Document` —
/// `flatten` and `deny_unknown_fields` don't compose in serde, and
/// "unknown fields are a clear error, not silent loss" is an explicit
/// acceptance criterion.
#[cfg(feature = "serde")]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct DocumentSchema {
    pub schema_version: u32,
    pub document: Document,
}

#[cfg(feature = "serde")]
#[derive(Debug)]
pub enum DocumentJsonError {
    /// `schema_version` isn't one this version of the crate understands.
    UnsupportedSchemaVersion(u32),
    /// `Document::to_json` on a `Document` with a `header`/`footer` set —
    /// neither is representable in JSON, so refusing beats silently
    /// dropping them.
    HeaderOrFooterNotSupported,
    /// `Document::to_json` on a `Document` with `zugferd_xml` set (issue
    /// #26) — not representable in JSON either, same reasoning.
    ZugferdXmlNotSupported,
    Json(serde_json::Error),
    /// From `Document::from_template` (issue #18): placeholder/`$each`
    /// resolution against the data tree failed before JSON parsing of
    /// the resolved document even started.
    Template(crate::template::TemplateError),
}

#[cfg(feature = "serde")]
impl std::fmt::Display for DocumentJsonError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DocumentJsonError::UnsupportedSchemaVersion(v) => {
                write!(
                    f,
                    "unsupported schema_version {v} (this crate understands {CURRENT_SCHEMA_VERSION})"
                )
            }
            DocumentJsonError::HeaderOrFooterNotSupported => {
                write!(
                    f,
                    "Document::to_json: header/footer aren't representable in the JSON schema (issue #17 V1 scope)"
                )
            }
            DocumentJsonError::ZugferdXmlNotSupported => {
                write!(
                    f,
                    "Document::to_json: zugferd_xml isn't representable in the JSON schema (issue #26)"
                )
            }
            DocumentJsonError::Json(e) => write!(f, "{e}"),
            DocumentJsonError::Template(e) => write!(f, "{e}"),
        }
    }
}

#[cfg(feature = "serde")]
impl std::error::Error for DocumentJsonError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            DocumentJsonError::Json(e) => Some(e),
            DocumentJsonError::Template(e) => Some(e),
            _ => None,
        }
    }
}

#[cfg(feature = "serde")]
impl Document {
    /// Parses `{"schema_version": N, "document": { .. }}`. Unknown fields
    /// anywhere in the tree are a clear error, never silently dropped.
    pub fn from_json(json: &str) -> Result<Document, DocumentJsonError> {
        let schema: DocumentSchema = serde_json::from_str(json).map_err(DocumentJsonError::Json)?;
        if schema.schema_version != CURRENT_SCHEMA_VERSION {
            return Err(DocumentJsonError::UnsupportedSchemaVersion(schema.schema_version));
        }
        Ok(schema.document)
    }

    /// `crate::template::render_template` + `from_json` in one call — a
    /// template document (with `{{path}}` placeholders and/or `$each`
    /// repetition, see the `template` module) plus a separate data
    /// document, no Rust code needed (issue #18).
    pub fn from_template(
        template_json: &str,
        data_json: &str,
        on_missing: crate::template::MissingPlaceholder,
    ) -> Result<Document, DocumentJsonError> {
        let resolved = crate::template::render_template(template_json, data_json, on_missing).map_err(DocumentJsonError::Template)?;
        Document::from_json(&resolved)
    }

    /// The inverse of `from_json` — round-trips to a byte-identical
    /// rendered PDF as long as neither `header` nor `footer` is set.
    pub fn to_json(&self) -> Result<String, DocumentJsonError> {
        if self.header.is_some() || self.footer.is_some() {
            return Err(DocumentJsonError::HeaderOrFooterNotSupported);
        }
        if self.zugferd_xml.is_some() {
            return Err(DocumentJsonError::ZugferdXmlNotSupported);
        }
        let schema = DocumentSchema {
            schema_version: CURRENT_SCHEMA_VERSION,
            document: self.clone(),
        };
        serde_json::to_string(&schema).map_err(DocumentJsonError::Json)
    }
}

#[cfg(all(test, feature = "serde"))]
mod json_tests {
    use super::*;
    use crate::element::Text;
    use crate::style::{Align, Color};

    fn sample_document() -> Document {
        let mut doc = Document::new(PageFormat::A4).margin(Margin::all(30.0)).title("Rechnung");
        doc.add(Text::new("Hello").size(18.0).color(Color::rgb(200, 0, 0)).align(Align::Center));
        doc
    }

    #[test]
    fn round_trip_preserves_page_format_and_children() {
        let json = sample_document().to_json().expect("to_json should succeed");
        assert!(
            json.contains("\"schema_version\":1"),
            "expected a versioned root field, got: {json}"
        );
        let doc = Document::from_json(&json).expect("from_json should succeed");
        assert_eq!(doc.page_format, PageFormat::A4);
        assert_eq!(doc.metadata.title.as_deref(), Some("Rechnung"));
        assert_eq!(doc.children.len(), 1);
        let Element::Text(t) = &doc.children[0] else {
            panic!("expected a Text child");
        };
        assert_eq!(t.content, "Hello");
        assert_eq!(t.style.size, 18.0);
        assert_eq!(t.style.color, Color::rgb(200, 0, 0));
        assert_eq!(t.style.align, Align::Center);
    }

    #[test]
    fn unknown_field_is_a_clear_error_not_silent_loss() {
        let json = r#"{"schema_version":1,"document":{"page_format":"A4","typo_field":true}}"#;
        let Err(err) = Document::from_json(json) else {
            panic!("an unknown field must be rejected");
        };
        let message = err.to_string();
        assert!(
            message.contains("typo_field") || message.contains("unknown field"),
            "expected the error to mention the unknown field, got: {message}"
        );
    }

    #[test]
    fn to_json_refuses_a_document_with_a_header() {
        let mut doc = sample_document();
        doc = doc.header(Header::new(20.0, |_| Element::Text(Text::new("Header"))));
        assert!(matches!(doc.to_json(), Err(DocumentJsonError::HeaderOrFooterNotSupported)));
    }

    #[test]
    fn unsupported_schema_version_is_rejected() {
        let json = r#"{"schema_version":99,"document":{"page_format":"A4"}}"#;
        assert!(matches!(
            Document::from_json(json),
            Err(DocumentJsonError::UnsupportedSchemaVersion(99))
        ));
    }
}