Nest PDF bookmarks by heading level

This commit is contained in:
gloamxun committed 2026-10-26 01:20:41 +08:00
1 parent 5f98c199a5
commit a4c4864d2b
5 files changed
+135 -20

No files matched your search

+114 -9
View File
@@ -3,8 +3,8 @@
//! Embedded true-type text faces, filled rectangles,
//! and raw-RGB image XObjects.
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::{BTreeMap, HashMap};
use std::io::Write as _;
use std::sync::OnceLock;
@@ -635,6 +635,8 @@ pub struct PdfMetadata {
pub struct PdfOutlineEntry {
pub title: String,
pub page: usize,
/// Heading depth, with 1 as the top level.
pub level: u8,
}
fn pdf_text(value: &str) -> String {
@@ -720,6 +722,17 @@ pub fn display_lists_to_pdf_with_paper(
)
}
fn descendant_count(children: &HashMap<usize, Vec<usize>>, node: usize) -> usize {
children
.get(&node)
.map(|kids| {
kids.iter()
.map(|kid| 1 + descendant_count(children, *kid))
.sum()
})
.unwrap_or(0)
}
/// Write PDFs with Knuth's Computer Modern Type1 outlines whenever the programs
/// cover the text, falling back to Liberation TrueType for other characters.
pub fn display_lists_to_pdf_with_cm_type1(
@@ -1070,32 +1083,72 @@ fn write_pdf(
objects.len()
})
.collect();
// Nest entries by heading level: an entry is a child of the nearest
// preceding entry with a strictly smaller level.
let mut parents: Vec<Option<usize>> = vec![None; metadata.outline.len()];
let mut stack: Vec<usize> = Vec::new();
let mut children: HashMap<usize, Vec<usize>> = HashMap::new();
for index in 0..metadata.outline.len() {
let level = metadata.outline[index].level;
while let Some(&top) = stack.last() {
if metadata.outline[top].level >= level {
stack.pop();
} else {
break;
}
}
let parent = stack.last().copied();
parents[index] = parent;
children
.entry(parent.unwrap_or(usize::MAX))
.or_default()
.push(index);
stack.push(index);
}
for (index, entry) in metadata.outline.iter().enumerate() {
let page_id = page_ids
.get(entry.page)
.or_else(|| page_ids.last())
.copied()
.unwrap_or(0);
let parent_id = parents[index].map_or(root_id, |parent| item_ids[parent]);
let mut dict = format!(
"<< /Title {} /Parent {} 0 R /Dest [{} 0 R /Fit]",
pdf_text(&entry.title),
root_id,
parent_id,
page_id
);
if index > 0 {
dict.push_str(&format!(" /Prev {} 0 R", item_ids[index - 1]));
let siblings = &children[&parents[index].unwrap_or(usize::MAX)];
if let Some(position) = siblings.iter().position(|candidate| *candidate == index) {
if position > 0 {
dict.push_str(&format!(" /Prev {} 0 R", item_ids[siblings[position - 1]]));
}
if position + 1 < siblings.len() {
dict.push_str(&format!(" /Next {} 0 R", item_ids[siblings[position + 1]]));
}
}
if index + 1 < item_ids.len() {
dict.push_str(&format!(" /Next {} 0 R", item_ids[index + 1]));
if let Some(kids) = children.get(&index) {
if !kids.is_empty() {
dict.push_str(&format!(
" /First {} 0 R /Last {} 0 R /Count {}",
item_ids[kids[0]],
item_ids[kids[kids.len() - 1]],
descendant_count(&children, index)
));
}
}
dict.push_str(" >>");
objects[item_ids[index] - 1] = dict.into_bytes();
}
let roots = &children[&usize::MAX];
objects[root_id - 1] = format!(
"<< /Type /Outlines /First {} 0 R /Last {} 0 R /Count {} >>",
item_ids[0],
item_ids[item_ids.len() - 1],
item_ids.len()
item_ids[roots[0]],
item_ids[roots[roots.len() - 1]],
metadata.outline.len()
)
.into_bytes();
objects[0] =
@@ -1225,10 +1278,12 @@ mod type1_pdf_tests {
PdfOutlineEntry {
title: "1 One".into(),
page: 0,
level: 1,
},
PdfOutlineEntry {
title: "2 Two".into(),
page: 1,
level: 1,
},
],
..PdfMetadata::default()
@@ -1291,6 +1346,56 @@ mod type1_pdf_tests {
assert!(pdf.contains("/Title <FEFF03A9"));
}
#[test]
fn nested_outline_entries_nest_by_level() {
let pages = vec![
DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
},
DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
},
];
let metadata = PdfMetadata {
outline: vec![
PdfOutlineEntry {
title: "1 One".into(),
page: 0,
level: 1,
},
PdfOutlineEntry {
title: "1.1 Sub".into(),
page: 0,
level: 2,
},
PdfOutlineEntry {
title: "2 Two".into(),
page: 1,
level: 1,
},
],
..PdfMetadata::default()
};
let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata(
&pages,
612 * 65536,
792 * 65536,
PageOrigin::default(),
&metadata,
))
.to_string();
assert!(pdf.contains("/Title (1.1 Sub)"));
assert!(pdf.contains("/Count 3"));
assert!(pdf.contains("/First"));
assert!(pdf.contains("/Last"));
}
fn type1_backend_embeds_computer_modern_outlines() {
let pdf = write(&[hello_list()]);
let text = String::from_utf8_lossy(&pdf);