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