1mod 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#[derive(Debug, Clone, Default)]
56pub struct RenderContext {
57 pub title: String,
60 pub language: Option<String>,
62 pub description: Option<String>,
64 pub authors: Vec<String>,
66 pub creator: Option<String>,
68 pub producer: Option<String>,
73 pub creation_date: Option<krilla::metadata::DateTime>,
79 pub date_string: Option<String>,
84 pub vars: HashMap<String, String>,
91 pub external_tagrefs: HashMap<String, ExternalTagref>,
94}
95
96pub(crate) struct TemplateContext<'a> {
98 pub page: usize,
99 pub total: usize,
100 pub title: &'a str,
101 pub chapter: &'a str,
103 pub section: &'a str,
105 pub date: &'a str,
109 pub vars: &'a HashMap<String, String>,
112}
113
114impl TemplateContext<'_> {
115 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 out.push('{');
152 out.push_str(&name);
153 out.push('}');
154 }
155 },
156 }
157 }
158 out
159 }
160}
161
162#[allow(unused_mut)] #[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#[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#[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 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 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 let fonts = fonts::Fonts::resolve(style);
238 let body_families: &'static [&'static str] = fonts.body;
239 let _code_families = text::CodeFamiliesGuard::install(fonts.code);
243 let hyphenator = hyphen::WordHyphenator::from_style(&style.hyphenation);
244
245 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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: ¤t_chapter,
562 section: ¤t_section,
563 date: &date_str,
564 vars: &ctx.vars,
565 };
566 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 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 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 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 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 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 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 let outline = build_outline(&all_outline);
720 document.set_outline(outline);
721
722 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 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 false
755}
756
757fn 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
878fn 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
913fn build_outline(points: &[(usize, emit::OutlinePoint)]) -> Outline {
925 let mut outline = Outline::new();
926 if points.is_empty() {
927 return outline;
928 }
929
930 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 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 while let Some((_, completed)) = stack.pop() {
953 flush_into(&mut stack, &mut outline, completed);
954 }
955 outline
956}
957
958fn 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 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; 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
1005type 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
1139fn 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
1190struct 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 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 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
1297fn 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
1339fn build_document(profile: PdfExportProfile) -> Document {
1342 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 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
1372fn 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
1407fn 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 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 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 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}