Skip to main content

markdoc_pdf/render/
mod.rs

1//! PDF rendering for transformed Markdoc documents.
2//!
3//! Three-pass pipeline:
4//!   1. **layout** ([`block::layout_document`]) — walk the rendered tree,
5//!      lay out each block via parley, return a flat `Vec<Block>` with
6//!      heights baked in.
7//!   2. **paginate** ([`paginate::paginate`]) — greedy split of blocks
8//!      into pages so the running height stays under the page budget.
9//!   3. **emit** ([`emit::emit_blocks`]) — open one krilla page per group
10//!      and draw the blocks.
11
12mod block;
13mod coverpage;
14mod crossref_labels;
15mod decoration;
16mod emit;
17mod external_tagrefs;
18mod fonts;
19mod highlight;
20mod hyphen;
21mod inline;
22#[cfg(feature = "mermaid")]
23mod mermaid;
24mod paginate;
25pub mod style;
26mod text;
27
28use std::collections::HashMap;
29
30use krilla::Document;
31use krilla::SerializeSettings;
32use krilla::action::{Action, LinkAction};
33use krilla::annotation::{Annotation, LinkAnnotation, Target};
34use krilla::configure::{Accessibility, Archival, ConfigurationBuilder};
35use krilla::destination::XyzDestination;
36use krilla::geom::{Point, Rect};
37use krilla::metadata::Metadata;
38use krilla::outline::{Outline, OutlineNode};
39use krilla::page::PageSettings;
40use krilla::tagging::{Tag, TagGroup, TagKind, TagTree, kind};
41use krilla::text::Font;
42use markdoc::types::RenderableTreeNode;
43use parley::{FontContext, LayoutContext};
44
45use style::{PdfExportProfile, TocPosition};
46
47use crate::assets::AssetResolver;
48
49use block::LayoutCtx;
50pub use external_tagrefs::ExternalTagref;
51pub use style::{FrontmatterColumn, FrontmatterTable, Style, StyleLoadError};
52
53/// Caller-supplied context that the renderer can interpolate into
54/// header/footer template strings and surface as PDF document metadata.
55#[derive(Debug, Clone, Default)]
56pub struct RenderContext {
57    /// Document title — substituted as `{title}` in header/footer
58    /// templates and emitted as the PDF's `/Title` metadata.
59    pub title: String,
60    /// Document language code (e.g. `"en-us"`). Required by PDF/A.
61    pub language: Option<String>,
62    /// Document description / abstract.
63    pub description: Option<String>,
64    /// Authors (combined into PDF `/Author` metadata).
65    pub authors: Vec<String>,
66    /// Application that created the document.
67    pub creator: Option<String>,
68    /// Library / pipeline that wrote the PDF bytes (`/Producer`).
69    /// Defaults to krilla's own string when `None`. Set this to
70    /// e.g. `"markdoc-pdf 0.1.0"` so support tooling can identify
71    /// which version of the renderer produced a given file.
72    pub producer: Option<String>,
73    /// Document creation date for the PDF metadata. If `None`, the
74    /// renderer falls back to the current system time so PDF/A docs
75    /// always carry a valid `/CreationDate`. Use `dates::parse_iso`
76    /// to convert from a frontmatter ISO date string, or
77    /// `dates::now()` to stamp the build time.
78    pub creation_date: Option<krilla::metadata::DateTime>,
79    /// String used for the `{date}` header/footer template variable.
80    /// Defaults to today's date in `YYYY-MM-DD` form. Override to
81    /// supply a localised or differently-formatted date (e.g.
82    /// `"3 May 2026"`).
83    pub date_string: Option<String>,
84    /// Caller-supplied template variables, looked up by name in
85    /// header/footer and cover-page template strings (`{my_var}`) after
86    /// the built-in tokens. Lets a caller surface arbitrary frontmatter
87    /// (version, hardware revision, a pre-computed copyright year span,
88    /// …) without the renderer knowing those field names. Unknown names
89    /// are left as literal `{name}` so typos are visible.
90    pub vars: HashMap<String, String>,
91    /// Website pages for `{% tag %}` ids. A `{% tagref %}` whose target
92    /// is not declared in this PDF becomes a link to `url`.
93    pub external_tagrefs: HashMap<String, ExternalTagref>,
94}
95
96/// Per-page template context built internally during emission.
97pub(crate) struct TemplateContext<'a> {
98    pub page: usize,
99    pub total: usize,
100    pub title: &'a str,
101    /// Latest h1 text seen on or before this page.
102    pub chapter: &'a str,
103    /// Latest h2 text seen on or before this page.
104    pub section: &'a str,
105    /// Document build date pre-formatted by the renderer (defaults to
106    /// the build's date as `YYYY-MM-DD`; can be overridden by the
107    /// caller in `RenderContext`).
108    pub date: &'a str,
109    /// Caller-supplied template variables (from `RenderContext::vars`),
110    /// consulted for any `{name}` not in the built-in set.
111    pub vars: &'a HashMap<String, String>,
112}
113
114impl TemplateContext<'_> {
115    /// Substitute `{page}`, `{total}`, `{title}`, `{chapter}`,
116    /// `{section}`, `{date}` into a template string. Unknown `{vars}`
117    /// are left as-is so authors can spot typos in their templates.
118    pub fn substitute(&self, template: &str) -> String {
119        let mut out = String::with_capacity(template.len());
120        let mut chars = template.chars().peekable();
121        while let Some(c) = chars.next() {
122            if c != '{' {
123                out.push(c);
124                continue;
125            }
126            let mut name = String::new();
127            let mut closed = false;
128            for next in chars.by_ref() {
129                if next == '}' {
130                    closed = true;
131                    break;
132                }
133                name.push(next);
134            }
135            if !closed {
136                out.push('{');
137                out.push_str(&name);
138                continue;
139            }
140            match name.as_str() {
141                "page" => out.push_str(&self.page.to_string()),
142                "total" => out.push_str(&self.total.to_string()),
143                "title" => out.push_str(self.title),
144                "chapter" => out.push_str(self.chapter),
145                "section" => out.push_str(self.section),
146                "date" => out.push_str(self.date),
147                other => match self.vars.get(other) {
148                    Some(v) => out.push_str(v),
149                    None => {
150                        // Unknown — leave literal so typos are visible.
151                        out.push('{');
152                        out.push_str(&name);
153                        out.push('}');
154                    }
155                },
156            }
157        }
158        out
159    }
160}
161
162/// Render a transformed Markdoc tree to PDF bytes using the given style.
163/// Media references resolve through the null resolver (placeholder text);
164/// for documents that contain images, use [`render_pdf_with_assets`].
165#[allow(unused_mut)] // krilla's Surface lint misfires; binding kept mut for clarity
166/// Errors surfaced by the final PDF serialisation pass. Layout itself is
167/// infallible by construction; krilla defers image stream encoding to
168/// `finish()`, so a corrupt embedded asset surfaces here — as an error the
169/// CLI reports cleanly, not a panic.
170#[derive(Debug, thiserror::Error)]
171pub enum RenderError {
172    #[error("{0}")]
173    Serialise(String),
174}
175
176pub fn render_pdf(root: &RenderableTreeNode, style: &Style) -> Result<Vec<u8>, RenderError> {
177    render_pdf_with(
178        root,
179        style,
180        block::null_resolver(),
181        &RenderContext::default(),
182    )
183}
184
185/// Render with a caller-supplied asset resolver. Equivalent to
186/// `render_pdf_with` with a default `RenderContext`.
187#[allow(unused_mut)]
188pub fn render_pdf_with_assets(
189    root: &RenderableTreeNode,
190    style: &Style,
191    assets: &dyn AssetResolver,
192) -> Result<Vec<u8>, RenderError> {
193    render_pdf_with(root, style, assets, &RenderContext::default())
194}
195
196/// Full-control entry: caller provides assets resolver and `RenderContext`
197/// (used for header/footer template substitution like `{title}`).
198#[allow(unused_mut)]
199pub fn render_pdf_with(
200    root: &RenderableTreeNode,
201    style: &Style,
202    assets: &dyn AssetResolver,
203    ctx: &RenderContext,
204) -> Result<Vec<u8>, RenderError> {
205    // Tag aliases are already resolved: markdoc's schema bundle renders an
206    // alias under its canonical tag's name, so `{% notice %}` arrives here
207    // as `callout` and the `match`es below need no arm of their own for it.
208    // Keeping that in the schema rather than here means a renderer cannot
209    // forget it.
210
211    let rewritten = if ctx.external_tagrefs.is_empty() {
212        None
213    } else {
214        Some(external_tagrefs::externalize_out_of_scope_tagrefs(
215            root,
216            &ctx.external_tagrefs,
217        ))
218    };
219    let root = rewritten.as_ref().unwrap_or(root);
220
221    let mut font_cx = FontContext::default();
222    let mut layout_cx = LayoutContext::new();
223    let mut font_cache: HashMap<u64, Font> = HashMap::new();
224
225    // Custom fonts: load every configured .ttf/.otf path into the
226    // font collection up-front so all subsequent layout passes see
227    // them. Failures are silent — fontique already logs.
228    if !style.font_paths.is_empty() {
229        font_cx
230            .collection
231            .load_fonts_from_paths(style.font_paths.iter().map(std::path::Path::new));
232    }
233    // Resolve every element's font families once, up front. Elements
234    // that don't override anything share the body slice, so this costs
235    // what the old single-list resolution did unless the style actually
236    // asks for per-element fonts. See `fonts::Fonts`.
237    let fonts = fonts::Fonts::resolve(style);
238    let body_families: &'static [&'static str] = fonts.body;
239    // Inline code is styled deep in layout where only a `TextStyle` is
240    // in scope; this hands it the resolved code families for the
241    // duration of the render and restores the previous list on drop.
242    let _code_families = text::CodeFamiliesGuard::install(fonts.code);
243    let hyphenator = hyphen::WordHyphenator::from_style(&style.hyphenation);
244
245    // 1. Layout.
246    let crossref_labels = crossref_labels::build_crossref_labels(root, &style.heading_numbering);
247    let (blocks, footnotes) = {
248        let mut lctx = LayoutCtx {
249            style,
250            font_cx: &mut font_cx,
251            layout_cx: &mut layout_cx,
252            assets,
253            next_heading: 0,
254            next_figure: 0,
255            next_table: 0,
256            pending_table_caption: None,
257            pending_figure_caption: None,
258            footnotes: Vec::new(),
259            body_families,
260            fonts: &fonts,
261            hyphenator: hyphenator.as_ref(),
262            heading_counters: [0; 6],
263            list_depth: 0,
264            cell_content_align: None,
265            crossref_labels: &crossref_labels,
266        };
267        let blocks = block::layout_document(root, &mut lctx);
268        (blocks, lctx.footnotes)
269    };
270
271    // Prepend a synthesised cover page when the style enables it.
272    // The coverpage builder pulls everything from RenderContext
273    // (title / description / authors / date) plus the configured logo,
274    // and ends with a PageBreak so body content starts on page 2.
275    let date_for_coverpage = ctx
276        .date_string
277        .clone()
278        .unwrap_or_else(crate::dates::today_yyyy_mm_dd);
279    let mut blocks = blocks;
280    let mut cover_page_count = 0usize;
281    if style.coverpage.enabled {
282        let mut fp = coverpage::build_coverpage_blocks(
283            style,
284            ctx,
285            fonts.coverpage,
286            assets,
287            &mut font_cx,
288            &mut layout_cx,
289            &date_for_coverpage,
290        );
291        cover_page_count = fp
292            .iter()
293            .filter(|b| matches!(b.draw, block::BlockDraw::PageBreak))
294            .count();
295        fp.append(&mut blocks);
296        blocks = fp;
297    }
298
299    // 2. Paginate. Reserve vertical space for any header/footer.
300    let header_reserved = style
301        .page_decoration
302        .header
303        .as_ref()
304        .map(|h| h.reserved_height())
305        .unwrap_or(0.0);
306    let footer_reserved = style
307        .page_decoration
308        .footer
309        .as_ref()
310        .map(|f| f.reserved_height())
311        .unwrap_or(0.0);
312    let banner_band_top = style.margin_y * 0.42;
313    let banner_reserved = style
314        .page_decoration
315        .banner
316        .as_ref()
317        .map(|b| (banner_band_top + b.height + 12.0 - style.margin_y).max(0.0))
318        .unwrap_or(0.0);
319    let page_budget = style.page_height
320        - 2.0 * style.margin_y
321        - header_reserved
322        - footer_reserved
323        - banner_reserved;
324    let body_start_y = style.margin_y + header_reserved + banner_reserved;
325    let inner_x = style.margin_x;
326    let inner_w = style.page_width - 2.0 * style.margin_x;
327
328    // A synthesised cover always uses its own first-page geometry. Previously
329    // this only kicked in when `coverpage.margin_x` / `margin_y` were set, so
330    // a default cover still reserved header/footer space — even with
331    // `skip_first_page`. Auto-fit heroes then overflowed onto page 2.
332    let cover_first_page = style.coverpage.enabled;
333    let cover_margin_y = style.coverpage.margin_y.unwrap_or(style.margin_y);
334    let cover_hf = if style.page_decoration.skip_first_page {
335        0.0
336    } else {
337        header_reserved + footer_reserved + banner_reserved
338    };
339    let first_page_budget = if cover_first_page {
340        style.page_height - 2.0 * cover_margin_y - cover_hf
341    } else {
342        page_budget
343    };
344    let first_page_start_y = if cover_first_page {
345        let hdr = if style.page_decoration.skip_first_page {
346            0.0
347        } else {
348            header_reserved + banner_reserved
349        };
350        cover_margin_y + hdr
351    } else {
352        body_start_y
353    };
354
355    let column_layout = if style.page_layout.columns > 1 {
356        Some(emit::PageColumnLayout {
357            columns: style.page_layout.columns,
358            column_width: (inner_w
359                - style.page_layout.gap * (style.page_layout.columns as f32 - 1.0))
360                / style.page_layout.columns as f32,
361            gap: style.page_layout.gap,
362        })
363    } else {
364        None
365    };
366
367    // Footnote-aware pagination: pool height is recomputed every time
368    // a block carrying footnote calls is added, so the body budget
369    // shrinks dynamically as footnotes accumulate.
370    let body_with_pools: Vec<(Vec<block::Block>, Vec<block::Block>)> = {
371        let footnotes = &footnotes;
372        paginate::paginate_with_footnotes(
373            blocks,
374            page_budget,
375            first_page_budget,
376            style.page_layout.columns,
377            |numbers| {
378                if numbers.is_empty() {
379                    return (0.0, Vec::new());
380                }
381                let mut entries: Vec<(u32, String)> = numbers
382                    .iter()
383                    .filter_map(|n| {
384                        footnotes
385                            .get((*n as usize).saturating_sub(1))
386                            .filter(|b| !b.is_empty())
387                            .map(|b| (*n, b.clone()))
388                    })
389                    .collect();
390                entries.sort_by_key(|(n, _)| *n);
391                entries.dedup_by_key(|(n, _)| *n);
392                let pool = block::build_footnote_pool_blocks(
393                    &entries,
394                    style,
395                    fonts.footnote,
396                    &mut font_cx,
397                    &mut layout_cx,
398                    inner_x,
399                    inner_w,
400                );
401                let h = block::pool_height(&pool);
402                (h, pool)
403            },
404        )
405    };
406
407    // ── Optional: synthesise & insert ToC / List of Figures / List of Tables ─
408    // Where the start-positioned front matter splits from the body: after
409    // the cover by default, or — when the document carries a `{% toc /%}`
410    // marker — after the page that marker falls on (so any front-matter
411    // sections before it, e.g. a copyright page, precede the ToC).
412    let split_at = body_with_pools
413        .iter()
414        .position(|(blocks, _)| {
415            blocks
416                .iter()
417                .any(|b| b.anchor_id.as_deref() == Some(block::TOC_MARKER_ANCHOR))
418        })
419        .map(|marker_page| marker_page + 1)
420        .unwrap_or(cover_page_count);
421    let any_section = style.toc.enabled || style.lof.enabled || style.lot.enabled;
422    let mut pages: Vec<(Vec<block::Block>, Vec<block::Block>)> = if any_section {
423        build_with_front_matter_pools(
424            body_with_pools,
425            style,
426            &fonts,
427            &mut font_cx,
428            &mut layout_cx,
429            page_budget,
430            split_at,
431        )
432    } else {
433        body_with_pools
434    };
435    // Trailing blank pages so the physical count matches the configured
436    // multiple (`pad_to_multiple`, or 2 when only `pad_to_even` is set).
437    // Each padding page carries the running header / footer (and watermark)
438    // like any other page, but has no body content. `total_pages` is taken
439    // AFTER padding so the `{total}` page-of count includes them.
440    for _ in 0..padding_page_count(pages.len(), style.padding_multiple()) {
441        pages.push((Vec::new(), Vec::new()));
442    }
443    let total_pages = pages.len();
444
445    // Where the last-page QR stamp lands: the last page carrying body content
446    // (never a blank duplex-padding page) — unless `include_padding_page` opts
447    // into the physical last page (the back of the last sheet).
448    let last_content_idx = pages.iter().rposition(|(b, _)| !b.is_empty());
449    let qr_page_idx = match &style.page_decoration.last_page_qr {
450        Some(q) if q.include_padding_page => total_pages.checked_sub(1),
451        _ => last_content_idx,
452    };
453
454    // 3. Emit. Each page collects link annotations and outline points
455    //    locally; outline points carry their page index so the final
456    //    outline tree can be built once all pages are emitted. We also
457    //    track `current_chapter` (latest h1 text) across pages so it
458    //    can be substituted into header/footer templates.
459    // Pre-pass: walk the paginated blocks just summing y positions to
460    // collect every anchor's (page_idx, y). This map is then used during
461    // emit to resolve `{% tagref %}` internal links (`href = "#id"`)
462    // to PDF GoTo destinations. We can't defer this until after the
463    // emit loop because annotations must be added before page.finish().
464    let anchor_map = collect_anchor_map(&pages, body_start_y, column_layout);
465
466    let mut document = build_document(style.pdf_export);
467    apply_metadata(&mut document, ctx);
468
469    // PDF/UA-1 (and good practice for accessibility tools) requires a
470    // structure tree describing the document's logical hierarchy. We
471    // collect tag-tree fragments per page and assemble them at the end.
472    let tagging_enabled = matches!(style.pdf_export, PdfExportProfile::UA1);
473    let mut document_children: Vec<krilla::tagging::Node> = Vec::new();
474
475    let mut all_outline: Vec<(usize, emit::OutlinePoint)> = Vec::new();
476    let mut current_chapter: String = String::new();
477    let mut current_section: String = String::new();
478    let mut media_cache: decoration::MediaCache = HashMap::new();
479    // Pre-format the document date once for `{date}` substitution.
480    // Caller-supplied string wins; otherwise we stamp today's date.
481    let date_str = ctx
482        .date_string
483        .clone()
484        .unwrap_or_else(crate::dates::today_yyyy_mm_dd);
485
486    for (page_idx, (page_blocks, pool_blocks)) in pages.iter().enumerate() {
487        let mut page = document
488            .start_page_with(PageSettings::from_wh(style.page_width, style.page_height).unwrap());
489        let mut links: Vec<emit::DeferredLink> = Vec::new();
490        let mut outline_pts: Vec<emit::OutlinePoint> = Vec::new();
491        let mut page_tags = emit::TagAccumulator::new(tagging_enabled);
492        {
493            let mut surface = page.surface();
494            // Watermark first so body + decoration paint over it.
495            if let Some(wm) = &style.watermark {
496                decoration::emit_watermark(
497                    &mut surface,
498                    style,
499                    fonts.watermark,
500                    wm,
501                    page_idx,
502                    &mut font_cx,
503                    &mut layout_cx,
504                    &mut font_cache,
505                    assets,
506                    &mut media_cache,
507                    tagging_enabled,
508                );
509            }
510            // The cover page (page 0) may start at its own top margin.
511            let page_start_y = if page_idx == 0 {
512                first_page_start_y
513            } else {
514                body_start_y
515            };
516            emit::emit_blocks(
517                &mut surface,
518                page_blocks,
519                page_start_y,
520                &mut font_cache,
521                &mut links,
522                &mut outline_pts,
523                &mut page_tags,
524                column_layout,
525            );
526
527            // Footnote pool: floats at the bottom of the printable
528            // area regardless of how much body text the page carries.
529            // Pool blocks contain a leading gap + separator rule plus
530            // one paragraph per footnote entry.
531            if !pool_blocks.is_empty() {
532                let pool_h = block::pool_height(pool_blocks);
533                let pool_top_y = body_start_y + page_budget - pool_h;
534                emit::emit_blocks(
535                    &mut surface,
536                    pool_blocks,
537                    pool_top_y,
538                    &mut font_cache,
539                    &mut links,
540                    &mut outline_pts,
541                    &mut page_tags,
542                    None,
543                );
544            }
545
546            // Update running chapter / section for this page (h1 → chapter,
547            // h2 → section). Whichever heading appears LAST on the page
548            // wins for that page's header/footer.
549            for pt in &outline_pts {
550                match pt.level {
551                    1 => current_chapter = pt.text.clone(),
552                    2 => current_section = pt.text.clone(),
553                    _ => {}
554                }
555            }
556
557            let tctx = TemplateContext {
558                page: page_idx + 1,
559                total: total_pages,
560                title: &ctx.title,
561                chapter: &current_chapter,
562                section: &current_section,
563                date: &date_str,
564                vars: &ctx.vars,
565            };
566            // Page-level decoration: skip on first page if configured. The
567            // duplex-padding page is decorated like any other (header /
568            // footer); it just has no body.
569            let draw_decoration = !(style.page_decoration.skip_first_page && page_idx == 0);
570            if draw_decoration {
571                if let Some(header) = &style.page_decoration.header {
572                    decoration::emit_header(
573                        &mut surface,
574                        style,
575                        fonts.header,
576                        header,
577                        &tctx,
578                        &mut font_cx,
579                        &mut layout_cx,
580                        &mut font_cache,
581                        assets,
582                        &mut media_cache,
583                        tagging_enabled,
584                    );
585                }
586                if let Some(footer) = &style.page_decoration.footer {
587                    decoration::emit_footer(
588                        &mut surface,
589                        style,
590                        fonts.footer,
591                        footer,
592                        &tctx,
593                        &mut font_cx,
594                        &mut layout_cx,
595                        &mut font_cache,
596                        assets,
597                        &mut media_cache,
598                        tagging_enabled,
599                    );
600                }
601                if let Some(banner) = &style.page_decoration.banner {
602                    decoration::emit_notice_banner(
603                        &mut surface,
604                        style,
605                        fonts.notice_banner,
606                        banner,
607                        banner_band_top,
608                        &tctx,
609                        &mut font_cx,
610                        &mut layout_cx,
611                        &mut font_cache,
612                        assets,
613                        &mut media_cache,
614                        tagging_enabled,
615                    );
616                }
617            }
618            // Last-page QR stamp — bottom-right corner of the final content
619            // page, drawn regardless of the header/footer skip logic.
620            if Some(page_idx) == qr_page_idx
621                && let Some(qr) = &style.page_decoration.last_page_qr
622            {
623                decoration::emit_last_page_qr(
624                    &mut surface,
625                    style,
626                    fonts.qr,
627                    qr,
628                    &tctx,
629                    &mut font_cx,
630                    &mut layout_cx,
631                    &mut font_cache,
632                    tagging_enabled,
633                );
634            }
635            surface.finish();
636        }
637        for link in links {
638            // Build the per-line rect list. Skip the link if every
639            // rect is malformed (e.g. zero-width sliver from a layout
640            // edge case).
641            let quads: Vec<krilla::geom::Quadrilateral> = link
642                .rects
643                .iter()
644                .filter_map(|(x, y, w, h)| Rect::from_xywh(*x, *y, *w, *h))
645                .map(krilla::geom::Quadrilateral::from)
646                .collect();
647            if quads.is_empty() {
648                continue;
649            }
650            // PDF/UA requires alt text on every annotation. Fall back
651            // to the href so the link is still self-describing.
652            let alt = link.alt.clone().or_else(|| Some(link.href.clone()));
653            let target = if let Some(id) = link.href.strip_prefix('#') {
654                match anchor_map.get(id) {
655                    Some((dest_page, dest_y)) => {
656                        Target::Action(Action::Goto(krilla::destination::Destination::Xyz(
657                            XyzDestination::new(*dest_page, Point::from_xy(0.0, *dest_y)),
658                        )))
659                    }
660                    None => Target::Action(Action::Link(LinkAction::new(link.href.clone()))),
661                }
662            } else {
663                Target::Action(Action::Link(LinkAction::new(link.href.clone())))
664            };
665            // Single-line links use a plain rect; wrapped links use
666            // quad_points so the annotation hot region follows the
667            // text shape rather than enclosing the gap between lines.
668            let link_annot = if quads.len() == 1 {
669                LinkAnnotation::new(
670                    Rect::from_xywh(
671                        link.rects[0].0,
672                        link.rects[0].1,
673                        link.rects[0].2,
674                        link.rects[0].3,
675                    )
676                    .unwrap(),
677                    target,
678                )
679            } else {
680                LinkAnnotation::new_with_quad_points(quads, target)
681            };
682            let annot = Annotation::new_link(link_annot, alt);
683            // For tagged docs, the annotation's structure-tree role is a
684            // single `Link` tag group whose children are every text Span
685            // identifier produced for this link (one per wrapped line)
686            // followed by the annotation identifier returned by
687            // add_tagged_annotation. Each identifier has exactly one
688            // parent in the tree, so the link's text identifiers are
689            // intentionally absent from the surrounding `P` group.
690            if tagging_enabled {
691                let annot_id = page.add_tagged_annotation(annot);
692                let mut link_group = TagGroup::new(TagKind::Link(Tag::<kind::Link>::Link));
693                for text_id in link.text_segment_ids {
694                    link_group.push(text_id);
695                }
696                link_group.push(annot_id);
697                page_tags.nodes.push(link_group.into());
698            } else {
699                page.add_annotation(annot);
700            }
701        }
702        for pt in outline_pts {
703            all_outline.push((page_idx, pt));
704        }
705        if tagging_enabled {
706            // Group all of this page's content tags into one Section,
707            // then push that into the document children.
708            let mut section = TagGroup::new(TagKind::Section(Tag::<kind::Section>::Section));
709            for n in page_tags.nodes {
710                section.push(n);
711            }
712            document_children.push(section.into());
713        }
714        page.finish();
715    }
716
717    // 4. Build the outline tree from collected (page_idx, level, text, y)
718    //    tuples and attach to the document.
719    let outline = build_outline(&all_outline);
720    document.set_outline(outline);
721
722    // 5. Build the tag tree (PDF/UA-1) from per-page tag fragments.
723    if tagging_enabled {
724        let mut tree = TagTree::new();
725        if let Some(lang) = ctx.language.clone() {
726            tree = tree.with_lang(Some(lang));
727        }
728        for n in document_children {
729            tree.push(n);
730        }
731        document.set_tag_tree(tree);
732    }
733
734    // Edge case: empty document → ensure at least one (blank) page exists
735    // so viewers don't choke on a zero-page PDF.
736    if document_has_no_pages(&document) {
737        let mut page = document
738            .start_page_with(PageSettings::from_wh(style.page_width, style.page_height).unwrap());
739        let mut surface = page.surface();
740        surface.finish();
741        page.finish();
742    }
743
744    document.finish().map_err(|e| {
745        RenderError::Serialise(format!(
746            "PDF serialisation failed (a corrupt embedded image is the usual cause): {e:?}"
747        ))
748    })
749}
750
751fn document_has_no_pages(_doc: &Document) -> bool {
752    // krilla doesn't expose a page count; track it externally if needed.
753    // For now, assume non-empty input always produces at least one page.
754    false
755}
756
757/// Walk paginated blocks (without rendering) to compute every anchor's
758/// page index and y position. Used to build the cross-reference map
759/// before per-page emit so internal `{% tagref %}` links can resolve
760/// to PDF GoTo destinations.
761fn collect_anchor_map(
762    pages: &[(Vec<block::Block>, Vec<block::Block>)],
763    body_start_y: f32,
764    columns: Option<emit::PageColumnLayout>,
765) -> std::collections::HashMap<String, (usize, f32)> {
766    let mut map = std::collections::HashMap::new();
767    for (page_idx, (page_blocks, _pool)) in pages.iter().enumerate() {
768        walk_anchors(page_blocks, page_idx, body_start_y, columns, &mut map);
769    }
770    map
771}
772
773fn walk_anchors(
774    blocks: &[block::Block],
775    page_idx: usize,
776    start_y: f32,
777    columns: Option<emit::PageColumnLayout>,
778    map: &mut std::collections::HashMap<String, (usize, f32)>,
779) {
780    if columns.map(|c| c.columns).unwrap_or(1) <= 1 {
781        walk_anchors_single(blocks, page_idx, start_y, map);
782        return;
783    }
784    let layout = columns.unwrap();
785    let n = layout.columns.max(1) as usize;
786    let mut col_y = vec![start_y; n];
787    for block in blocks {
788        let col_idx = block.page_column.min(layout.columns.saturating_sub(1)) as usize;
789        let y = if block.column_span {
790            col_y.iter().copied().fold(start_y, f32::max)
791        } else {
792            col_y[col_idx]
793        };
794        record_block_anchors(block, page_idx, y, map);
795        let advance = block.height + block.space_after;
796        if block.column_span {
797            let new_y = y + advance;
798            col_y.fill(new_y);
799        } else {
800            col_y[col_idx] = y + advance;
801        }
802    }
803}
804
805fn walk_anchors_single(
806    blocks: &[block::Block],
807    page_idx: usize,
808    start_y: f32,
809    map: &mut std::collections::HashMap<String, (usize, f32)>,
810) {
811    let mut y = start_y;
812    for block in blocks {
813        record_block_anchors(block, page_idx, y, map);
814        y += block.height + block.space_after;
815    }
816}
817
818fn record_block_anchors(
819    block: &block::Block,
820    page_idx: usize,
821    y: f32,
822    map: &mut std::collections::HashMap<String, (usize, f32)>,
823) {
824    if let Some(id) = &block.anchor_id {
825        map.entry(id.clone()).or_insert((page_idx, y));
826    }
827    match &block.draw {
828        block::BlockDraw::Text(slice) if !slice.mid_anchors.is_empty() => {
829            for anchor in slice.mid_anchors.iter() {
830                if let Some(line_y_offset) = mid_anchor_y_in_slice(slice, anchor.byte_offset) {
831                    map.entry(anchor.id.clone())
832                        .or_insert((page_idx, y + line_y_offset));
833                }
834            }
835        }
836        block::BlockDraw::BoxedGroup {
837            children, padding, ..
838        } => {
839            walk_anchors_single(children, page_idx, y + *padding, map);
840        }
841        block::BlockDraw::ListItem { body, .. } => {
842            walk_anchors_single(body, page_idx, y, map);
843        }
844        block::BlockDraw::Table {
845            rows,
846            cell_padding,
847            border_thickness,
848            ..
849        } => {
850            let mut row_top = y + *border_thickness;
851            for row in rows {
852                for cell in &row.cells {
853                    walk_anchors_single(&cell.blocks, page_idx, row_top + *cell_padding, map);
854                }
855                row_top += row.height + *border_thickness;
856            }
857        }
858        block::BlockDraw::Float { image, wrap } => {
859            walk_anchors_single(std::slice::from_ref(image.as_ref()), page_idx, y, map);
860            walk_anchors_single(wrap, page_idx, y, map);
861        }
862        block::BlockDraw::FloatRegion { text, floats } => {
863            for anchor in text.mid_anchors.iter() {
864                if let Some(dy) = mid_anchor_y_in_slice(text, anchor.byte_offset) {
865                    map.entry(anchor.id.clone()).or_insert((page_idx, y + dy));
866                }
867            }
868            for fl in floats {
869                if let Some(id) = &fl.image.anchor_id {
870                    map.entry(id.clone()).or_insert((page_idx, y + fl.y_offset));
871                }
872            }
873        }
874        _ => {}
875    }
876}
877
878/// Find the y offset (relative to a slice's drawn top) where the line
879/// containing `byte_offset` begins. Returns `None` if the byte falls
880/// outside this slice's `line_range` (the anchor lives in another
881/// slice from a split paragraph).
882fn mid_anchor_y_in_slice(slice: &block::TextSlice, byte_offset: usize) -> Option<f32> {
883    let line_idx = find_line_for_byte(&slice.layout, byte_offset);
884    if line_idx < slice.line_range.start || line_idx >= slice.line_range.end {
885        return None;
886    }
887    let y: f32 = slice.line_heights[slice.line_range.start..line_idx]
888        .iter()
889        .copied()
890        .sum();
891    Some(y)
892}
893
894fn find_line_for_byte(layout: &parley::Layout<krilla::color::rgb::Color>, byte: usize) -> usize {
895    let mut last = 0usize;
896    for (i, line) in layout.lines().enumerate() {
897        last = i;
898        for run in line.runs() {
899            for cluster in run.visual_clusters() {
900                let r = cluster.text_range();
901                if byte >= r.start && byte < r.end {
902                    return i;
903                }
904                if byte == r.end {
905                    return i;
906                }
907            }
908        }
909    }
910    last
911}
912
913/// Build a hierarchical PDF outline from flat heading entries.
914///
915/// Algorithm: walk entries in source order maintaining a stack of
916/// (level, in-progress OutlineNode). For each new heading:
917///   - pop the stack while top.level >= new.level
918///   - if stack non-empty, attach the new node as a child of top
919///   - else push as a top-level node when complete
920///
921/// Because OutlineNode children are immutable once attached, we keep
922/// a parallel stack of "open" nodes whose children we still mutate, and
923/// flush them to their parent / the outline root when popped.
924fn build_outline(points: &[(usize, emit::OutlinePoint)]) -> Outline {
925    let mut outline = Outline::new();
926    if points.is_empty() {
927        return outline;
928    }
929
930    // Stack: each entry is (level, partially-built OutlineNode).
931    let mut stack: Vec<(u8, OutlineNode)> = Vec::new();
932
933    let flush_into = |stack: &mut Vec<(u8, OutlineNode)>, out: &mut Outline, node: OutlineNode| {
934        if let Some(parent) = stack.last_mut() {
935            parent.1.push_child(node);
936        } else {
937            out.push_child(node);
938        }
939    };
940
941    for (page_idx, pt) in points {
942        // Pop deeper-or-equal-level nodes until parent has a strictly
943        // smaller level.
944        while stack.last().is_some_and(|(lvl, _)| *lvl >= pt.level) {
945            let (_, completed) = stack.pop().unwrap();
946            flush_into(&mut stack, &mut outline, completed);
947        }
948        let dest = XyzDestination::new(*page_idx, Point::from_xy(0.0, pt.y));
949        stack.push((pt.level, OutlineNode::new(pt.text.clone(), dest)));
950    }
951    // Flush remaining nodes.
952    while let Some((_, completed)) = stack.pop() {
953        flush_into(&mut stack, &mut outline, completed);
954    }
955    outline
956}
957
958/// Build any combination of ToC / List of Figures / List of Tables
959/// from the paginated body, paginate each section, and concatenate
960/// them in canonical order (ToC → LoF → LoT) at start or end.
961///
962/// Page numbers in the section entries reflect the FINAL PDF page
963/// numbers, accounting for the combined start-placement section
964/// length. We iterate up to 4 times to converge — single-digit ↔
965/// double-digit transitions can in theory shift pagination, but in
966/// practice everything stabilises in 1 pass.
967/// Pool-aware wrapper around [`build_with_front_matter`]. Body pages
968/// carry the pool the paginator built for them; front-matter pages
969/// pair with an empty pool (ToC/LoF/LoT never reference footnotes).
970fn build_with_front_matter_pools(
971    mut body_with_pools: Vec<(Vec<block::Block>, Vec<block::Block>)>,
972    style: &Style,
973    fonts: &fonts::Fonts,
974    font_cx: &mut FontContext,
975    layout_cx: &mut LayoutContext<krilla::color::rgb::Color>,
976    page_budget: f32,
977    split_at: usize,
978) -> Vec<(Vec<block::Block>, Vec<block::Block>)> {
979    let body_pages: Vec<Vec<block::Block>> =
980        body_with_pools.iter().map(|(b, _)| b.clone()).collect();
981    let (start_pages, _body_through, end_pages) = build_front_matter_split(
982        body_pages,
983        style,
984        fonts,
985        font_cx,
986        layout_cx,
987        page_budget,
988        split_at,
989    );
990
991    // The leading `split_at` body pages — the cover plus any front matter
992    // before a `{% toc /%}` marker — come first; start-positioned ToC /
993    // LoF / LoT slot in *after* them, and the rest of the body follows.
994    let k = split_at.min(body_with_pools.len());
995    let rest_body = body_with_pools.split_off(k);
996    let leading_pages = body_with_pools; // the leading `k` (body, pool) pages
997
998    let mut out = leading_pages;
999    out.extend(start_pages.into_iter().map(|p| (p, Vec::new())));
1000    out.extend(rest_body);
1001    out.extend(end_pages.into_iter().map(|p| (p, Vec::new())));
1002    out
1003}
1004
1005/// Variant of [`build_with_front_matter`] that returns the
1006/// `(start_pages, body_pages, end_pages)` split so the caller can
1007/// re-attach footnote pools to body pages without re-locating them in
1008/// the concatenated output.
1009/// Three sets of "front matter" pages — table of contents, list of
1010/// figures, list of tables — extracted from the body pages and laid out
1011/// independently. Each outer `Vec` is the pages, inner is the blocks on
1012/// that page.
1013type FrontMatterPages = (
1014    Vec<Vec<block::Block>>,
1015    Vec<Vec<block::Block>>,
1016    Vec<Vec<block::Block>>,
1017);
1018
1019fn build_front_matter_split(
1020    body_pages: Vec<Vec<block::Block>>,
1021    style: &Style,
1022    fonts: &fonts::Fonts,
1023    font_cx: &mut FontContext,
1024    layout_cx: &mut LayoutContext<krilla::color::rgb::Color>,
1025    page_budget: f32,
1026    split_at: usize,
1027) -> FrontMatterPages {
1028    let headings = harvest_heading_entries(&body_pages);
1029    let figures = harvest_figure_entries(&body_pages);
1030    let tables = harvest_table_entries(&body_pages);
1031
1032    let mut start_offset: usize = if any_start_section_enabled(style) {
1033        1
1034    } else {
1035        0
1036    };
1037
1038    let mut start_pages: Vec<Vec<block::Block>> = Vec::new();
1039    let mut end_pages: Vec<Vec<block::Block>> = Vec::new();
1040
1041    for _ in 0..4 {
1042        start_pages.clear();
1043        end_pages.clear();
1044
1045        if style.toc.enabled {
1046            let entries: Vec<block::TocEntry> = headings
1047                .iter()
1048                .map(|h| block::TocEntry {
1049                    level: h.level,
1050                    text: h.text.clone(),
1051                    target_anchor_id: h.anchor_id.clone(),
1052                    page_number: page_number_for(
1053                        h.body_page_idx,
1054                        style.toc.position,
1055                        start_offset,
1056                        split_at,
1057                    ),
1058                })
1059                .collect();
1060            let blocks = block::build_toc_blocks(&entries, style, fonts.toc, font_cx, layout_cx);
1061            let pages = paginate::paginate(blocks, page_budget);
1062            push_section(&mut start_pages, &mut end_pages, style.toc.position, pages);
1063        }
1064        if style.lof.enabled {
1065            let entries: Vec<block::TocEntry> = figures
1066                .iter()
1067                .enumerate()
1068                .map(|(i, f)| block::TocEntry {
1069                    level: 1,
1070                    text: figure_caption(i, f, style),
1071                    target_anchor_id: f.anchor_id.clone(),
1072                    page_number: page_number_for(
1073                        f.body_page_idx,
1074                        style.lof.position,
1075                        start_offset,
1076                        split_at,
1077                    ),
1078                })
1079                .collect();
1080            let blocks = block::build_list_section_blocks(
1081                style.lof.resolved_title("List of Figures"),
1082                style.lof.title_font_size,
1083                style.lof.entry_font_size,
1084                style.lof.entry_space_after,
1085                &entries,
1086                style,
1087                fonts.lof,
1088                font_cx,
1089                layout_cx,
1090            );
1091            let pages = paginate::paginate(blocks, page_budget);
1092            push_section(&mut start_pages, &mut end_pages, style.lof.position, pages);
1093        }
1094        if style.lot.enabled {
1095            let entries: Vec<block::TocEntry> = tables
1096                .iter()
1097                .enumerate()
1098                .map(|(i, t)| block::TocEntry {
1099                    level: 1,
1100                    text: table_caption(i, t, style),
1101                    target_anchor_id: t.anchor_id.clone(),
1102                    page_number: page_number_for(
1103                        t.body_page_idx,
1104                        style.lot.position,
1105                        start_offset,
1106                        split_at,
1107                    ),
1108                })
1109                .collect();
1110            let blocks = block::build_list_section_blocks(
1111                style.lot.resolved_title("List of Tables"),
1112                style.lot.title_font_size,
1113                style.lot.entry_font_size,
1114                style.lot.entry_space_after,
1115                &entries,
1116                style,
1117                fonts.lot,
1118                font_cx,
1119                layout_cx,
1120            );
1121            let pages = paginate::paginate(blocks, page_budget);
1122            push_section(&mut start_pages, &mut end_pages, style.lot.position, pages);
1123        }
1124        let new_offset = start_pages.len();
1125        if new_offset == start_offset {
1126            break;
1127        }
1128        start_offset = new_offset;
1129    }
1130    (start_pages, body_pages, end_pages)
1131}
1132
1133fn any_start_section_enabled(style: &Style) -> bool {
1134    (style.toc.enabled && style.toc.position == TocPosition::Start)
1135        || (style.lof.enabled && style.lof.position == TocPosition::Start)
1136        || (style.lot.enabled && style.lot.position == TocPosition::Start)
1137}
1138
1139/// Final 1-based page number for a heading on body page `body_idx`.
1140///
1141/// For a start-positioned ToC, the `start_offset` ToC pages sit at
1142/// `split_at` (after the leading cover / front-matter pages). A heading
1143/// in those leading pages (`body_idx < split_at`) keeps its natural
1144/// number; a heading after the split is pushed down by `start_offset`.
1145fn page_number_for(
1146    body_idx: usize,
1147    position: TocPosition,
1148    start_offset: usize,
1149    split_at: usize,
1150) -> usize {
1151    match position {
1152        TocPosition::End => body_idx + 1,
1153        TocPosition::Start if body_idx < split_at => body_idx + 1,
1154        TocPosition::Start => body_idx + start_offset + 1,
1155    }
1156}
1157
1158fn push_section(
1159    start: &mut Vec<Vec<block::Block>>,
1160    end: &mut Vec<Vec<block::Block>>,
1161    position: TocPosition,
1162    pages: Vec<Vec<block::Block>>,
1163) {
1164    match position {
1165        TocPosition::Start => start.extend(pages),
1166        TocPosition::End => end.extend(pages),
1167    }
1168}
1169
1170fn figure_caption(index: usize, f: &FigureEntry, style: &Style) -> String {
1171    let n = index + 1;
1172    let prefix = &style.figure_caption_prefix;
1173    let sep = &style.caption_separator;
1174    match &f.caption {
1175        Some(c) if !c.trim().is_empty() => format!("{prefix} {n}{sep} {}", c.trim()),
1176        _ => format!("{prefix} {n}"),
1177    }
1178}
1179
1180fn table_caption(index: usize, t: &TableEntry, style: &Style) -> String {
1181    let n = index + 1;
1182    let prefix = &style.table_caption_prefix;
1183    let sep = &style.caption_separator;
1184    match &t.caption {
1185        Some(c) if !c.trim().is_empty() => format!("{prefix} {n}{sep} {}", c.trim()),
1186        _ => format!("{prefix} {n}"),
1187    }
1188}
1189
1190/// One heading harvested from the paginated body: text, level, anchor
1191/// id (for linking), and the body-relative page index.
1192struct HeadingEntry {
1193    level: u8,
1194    text: String,
1195    anchor_id: String,
1196    body_page_idx: usize,
1197}
1198
1199struct FigureEntry {
1200    caption: Option<String>,
1201    anchor_id: String,
1202    body_page_idx: usize,
1203}
1204
1205struct TableEntry {
1206    anchor_id: String,
1207    body_page_idx: usize,
1208    caption: Option<String>,
1209}
1210
1211fn harvest_figure_entries(pages: &[Vec<block::Block>]) -> Vec<FigureEntry> {
1212    let mut out = Vec::new();
1213    for (page_idx, page) in pages.iter().enumerate() {
1214        walk_for_figures(page, page_idx, &mut out);
1215    }
1216    out
1217}
1218
1219fn walk_for_figures(blocks: &[block::Block], page_idx: usize, out: &mut Vec<FigureEntry>) {
1220    for block in blocks {
1221        let (caption, is_figure) = match &block.draw {
1222            block::BlockDraw::Image { caption, .. } => (caption.clone(), true),
1223            block::BlockDraw::Svg { caption, .. } => (caption.clone(), true),
1224            _ => (None, false),
1225        };
1226        if is_figure && let Some(id) = &block.anchor_id {
1227            out.push(FigureEntry {
1228                caption,
1229                anchor_id: id.clone(),
1230                body_page_idx: page_idx,
1231            });
1232        }
1233        // Recurse — figures can sit inside callouts, list items, table cells.
1234        match &block.draw {
1235            block::BlockDraw::BoxedGroup { children, .. } => {
1236                walk_for_figures(children, page_idx, out);
1237            }
1238            block::BlockDraw::ListItem { body, .. } => {
1239                walk_for_figures(body, page_idx, out);
1240            }
1241            block::BlockDraw::Table { rows, .. } => {
1242                for row in rows {
1243                    for cell in &row.cells {
1244                        walk_for_figures(&cell.blocks, page_idx, out);
1245                    }
1246                }
1247            }
1248            block::BlockDraw::Float { image, wrap } => {
1249                // The floated image is a figure; the wrap may hold more.
1250                walk_for_figures(std::slice::from_ref(image.as_ref()), page_idx, out);
1251                walk_for_figures(wrap, page_idx, out);
1252            }
1253            block::BlockDraw::FloatRegion { floats, .. } => {
1254                for fl in floats {
1255                    walk_for_figures(std::slice::from_ref(fl.image.as_ref()), page_idx, out);
1256                }
1257            }
1258            _ => {}
1259        }
1260    }
1261}
1262
1263fn harvest_table_entries(pages: &[Vec<block::Block>]) -> Vec<TableEntry> {
1264    let mut out = Vec::new();
1265    for (page_idx, page) in pages.iter().enumerate() {
1266        walk_for_tables(page, page_idx, &mut out);
1267    }
1268    out
1269}
1270
1271fn walk_for_tables(blocks: &[block::Block], page_idx: usize, out: &mut Vec<TableEntry>) {
1272    for block in blocks {
1273        if let block::BlockDraw::Table { caption, .. } = &block.draw
1274            && let Some(id) = &block.anchor_id
1275        {
1276            out.push(TableEntry {
1277                anchor_id: id.clone(),
1278                body_page_idx: page_idx,
1279                caption: caption.clone(),
1280            });
1281        }
1282        match &block.draw {
1283            block::BlockDraw::BoxedGroup { children, .. } => {
1284                walk_for_tables(children, page_idx, out);
1285            }
1286            block::BlockDraw::ListItem { body, .. } => {
1287                walk_for_tables(body, page_idx, out);
1288            }
1289            block::BlockDraw::Float { wrap, .. } => {
1290                walk_for_tables(wrap, page_idx, out);
1291            }
1292            _ => {}
1293        }
1294    }
1295}
1296
1297/// Walk paginated body blocks to harvest every heading entry with its
1298/// page index. Used to seed the TOC.
1299fn harvest_heading_entries(pages: &[Vec<block::Block>]) -> Vec<HeadingEntry> {
1300    let mut out = Vec::new();
1301    for (page_idx, page) in pages.iter().enumerate() {
1302        walk_for_headings(page, page_idx, &mut out);
1303    }
1304    out
1305}
1306
1307fn walk_for_headings(blocks: &[block::Block], page_idx: usize, out: &mut Vec<HeadingEntry>) {
1308    for block in blocks {
1309        if let (Some(entry), Some(id)) = (&block.outline, &block.anchor_id) {
1310            out.push(HeadingEntry {
1311                level: entry.level,
1312                text: entry.text.clone(),
1313                anchor_id: id.clone(),
1314                body_page_idx: page_idx,
1315            });
1316        }
1317        match &block.draw {
1318            block::BlockDraw::BoxedGroup { children, .. } => {
1319                walk_for_headings(children, page_idx, out);
1320            }
1321            block::BlockDraw::ListItem { body, .. } => {
1322                walk_for_headings(body, page_idx, out);
1323            }
1324            block::BlockDraw::Table { rows, .. } => {
1325                for row in rows {
1326                    for cell in &row.cells {
1327                        walk_for_headings(&cell.blocks, page_idx, out);
1328                    }
1329                }
1330            }
1331            block::BlockDraw::Float { wrap, .. } => {
1332                walk_for_headings(wrap, page_idx, out);
1333            }
1334            _ => {}
1335        }
1336    }
1337}
1338
1339/// Construct a krilla `Document` configured for the requested PDF
1340/// export profile (PDF/A variant, etc.). Default is unvalidated.
1341fn build_document(profile: PdfExportProfile) -> Document {
1342    // krilla 0.8 splits validation into independent archival (PDF/A) and
1343    // accessibility (PDF/UA) families, built via `ConfigurationBuilder`.
1344    let builder = match profile {
1345        PdfExportProfile::None => return Document::new(),
1346        PdfExportProfile::A1B => {
1347            ConfigurationBuilder::new().with_archival_validator(Archival::A1_B)
1348        }
1349        PdfExportProfile::A2B => {
1350            ConfigurationBuilder::new().with_archival_validator(Archival::A2_B)
1351        }
1352        PdfExportProfile::A3B => {
1353            ConfigurationBuilder::new().with_archival_validator(Archival::A3_B)
1354        }
1355        PdfExportProfile::A4 => ConfigurationBuilder::new().with_archival_validator(Archival::A4),
1356        PdfExportProfile::UA1 => {
1357            ConfigurationBuilder::new().with_accessibility_validator(Accessibility::UA1)
1358        }
1359    };
1360    // Each profile sets a single validator with a valid PDF-version range,
1361    // so `finish` can't fail here.
1362    let configuration = builder
1363        .finish()
1364        .expect("single validator always yields a valid configuration");
1365    let settings = SerializeSettings {
1366        configuration,
1367        ..Default::default()
1368    };
1369    Document::new_with(settings)
1370}
1371
1372/// Apply caller-supplied document metadata. Required for PDF/A
1373/// compliance (title + language + creation date); harmless for plain export.
1374fn apply_metadata(document: &mut Document, ctx: &RenderContext) {
1375    let mut meta = Metadata::new();
1376    let creation = ctx.creation_date.unwrap_or_else(crate::dates::now);
1377    meta = meta.creation_date(creation);
1378    if !ctx.title.is_empty() {
1379        meta = meta.title(ctx.title.clone());
1380    }
1381    if let Some(lang) = ctx.language.clone()
1382        && !lang.is_empty()
1383    {
1384        meta = meta.language(lang);
1385    }
1386    if let Some(desc) = ctx.description.clone()
1387        && !desc.is_empty()
1388    {
1389        meta = meta.description(desc);
1390    }
1391    if !ctx.authors.is_empty() {
1392        meta = meta.authors(ctx.authors.clone());
1393    }
1394    if let Some(creator) = ctx.creator.clone()
1395        && !creator.is_empty()
1396    {
1397        meta = meta.creator(creator);
1398    }
1399    if let Some(producer) = ctx.producer.clone()
1400        && !producer.is_empty()
1401    {
1402        meta = meta.producer(producer);
1403    }
1404    document.set_metadata(meta);
1405}
1406
1407/// How many blank pages to append so `content_pages` is a multiple of
1408/// `multiple`. `multiple <= 1` or an empty document (0 pages) adds nothing.
1409fn padding_page_count(content_pages: usize, multiple: usize) -> usize {
1410    if multiple <= 1 || content_pages == 0 {
1411        return 0;
1412    }
1413    let rem = content_pages % multiple;
1414    if rem == 0 { 0 } else { multiple - rem }
1415}
1416
1417#[cfg(test)]
1418mod tests {
1419    use super::padding_page_count;
1420    use super::style::Style;
1421
1422    #[test]
1423    fn padding_page_count_even_and_booklet() {
1424        // Multiple of 2 (duplex): one blank when odd, none when even.
1425        assert_eq!(padding_page_count(1, 2), 1);
1426        assert_eq!(padding_page_count(3, 2), 1);
1427        assert_eq!(padding_page_count(2, 2), 0);
1428        assert_eq!(padding_page_count(6, 2), 0);
1429        // Multiple of 4 (booklet): 1–3 blanks until the count is divisible by 4.
1430        assert_eq!(padding_page_count(1, 4), 3);
1431        assert_eq!(padding_page_count(2, 4), 2);
1432        assert_eq!(padding_page_count(3, 4), 1);
1433        assert_eq!(padding_page_count(4, 4), 0);
1434        assert_eq!(padding_page_count(5, 4), 3);
1435        assert_eq!(padding_page_count(6, 4), 2);
1436        assert_eq!(padding_page_count(7, 4), 1);
1437        assert_eq!(padding_page_count(8, 4), 0);
1438        // Empty document and disabled multiple add nothing.
1439        assert_eq!(padding_page_count(0, 4), 0);
1440        assert_eq!(padding_page_count(3, 0), 0);
1441        assert_eq!(padding_page_count(3, 1), 0);
1442    }
1443
1444    #[test]
1445    fn padding_multiple_prefers_explicit_over_even() {
1446        let mut style = Style::default();
1447        assert_eq!(style.padding_multiple(), 0);
1448        style.pad_to_even = true;
1449        assert_eq!(style.padding_multiple(), 2);
1450        style.pad_to_multiple = 4;
1451        assert_eq!(style.padding_multiple(), 4);
1452    }
1453}