Embed fonts and add PDF link annotations

This commit is contained in:
gloamxun committed 2026-10-19 21:18:58 +08:00
1 parent 2856506d65
commit 3b270d749d
6 files changed
+247 -12

No files matched your search

+212 -3
View File
@@ -522,6 +522,144 @@ impl PositionedPages {
}
}
#[derive(Clone, Debug)]
struct LinkAnnotation {
page: u32,
rect: [f64; 4],
url: String,
}
impl PositionedPages {
/// Collect link rectangles for visible URL text. Links whose label is not a
/// URL (ORCID author names, citation keys) still need a target URL in the
/// model and are not annotated here.
fn link_annotations(
&self,
fonts: &fonts::FontCache,
page_height_mm: f64,
) -> Vec<LinkAnnotation> {
let mut annotations = Vec::new();
for (index, page) in self.pages.iter().enumerate() {
for item in &page.items {
match item {
PositionedPageItem::Line(line) => {
if line.anchor.block == usize::MAX {
continue;
}
let PositionedLineContent::Text {
line: content,
font_size,
} = &line.content
else {
continue;
};
let mut text_line = text_layout::TextLine::new(
content,
self.cjk_family.clone(),
self.mono_family.clone(),
self.sans_family.clone(),
*font_size,
);
if line.centered {
text_line = text_line.centered();
}
if line.ragged {
text_line = text_line.ragged();
}
let layout = text_line.layout_spans(fonts);
push_url_annotations(
&mut annotations,
&layout,
fonts,
scaled_units_to_mm(line.x),
scaled_units_to_mm(line.y),
*font_size,
index as u32 + 1,
page_height_mm,
);
}
PositionedPageItem::Centered { element, y, .. } => {
let font_size = 11;
let em = f64::from(font_size) * 25.4 / 72.27;
let mut line_y = scaled_units_to_mm(*y);
for line in &element.lines {
let text_line = text_layout::TextLine::new(
line,
self.cjk_family.clone(),
self.mono_family.clone(),
self.sans_family.clone(),
font_size,
)
.centered();
let layout = text_line.layout_spans(fonts);
push_url_annotations(
&mut annotations,
&layout,
fonts,
0.0,
line_y + em * 0.8,
font_size,
index as u32 + 1,
page_height_mm,
);
line_y += em * 1.2;
}
}
_ => {}
}
}
}
annotations
}
}
fn push_url_annotations(
annotations: &mut Vec<LinkAnnotation>,
layout: &text_layout::TextLineLayout,
fonts: &fonts::FontCache,
line_x_mm: f64,
baseline_mm: f64,
font_size: u8,
page: u32,
page_height_mm: f64,
) {
let mut fragments: Vec<(String, f64, f64)> = Vec::new();
let em = f64::from(font_size) * 25.4 / 72.27;
let flush = |fragments: &mut Vec<(String, f64, f64)>, annotations: &mut Vec<LinkAnnotation>| {
if fragments.is_empty() {
return;
}
let url = fragments
.iter()
.map(|(text, _, _)| text.as_str())
.collect::<String>();
if url.starts_with("http://") || url.starts_with("https://") {
for (_, x, width) in fragments.iter() {
let left = line_x_mm + *x;
annotations.push(LinkAnnotation {
page,
rect: [
left,
page_height_mm - (baseline_mm + em * 0.2),
left + *width,
page_height_mm - (baseline_mm - em * 0.8),
],
url: url.clone(),
});
}
}
fragments.clear();
};
for span in &layout.spans {
if !span.link {
flush(&mut fragments, annotations);
continue;
}
let width = span.style.str_width(fonts, &span.text);
fragments.push((span.text.clone(), f64::from(span.x), f64::from(width)));
}
flush(&mut fragments, annotations);
}
impl Element for PositionedPages {
fn render(
&mut self,
@@ -2193,7 +2331,7 @@ pub(super) fn render_pdf(
sans_family,
..
} = resources;
document.push(PositionedPages::new(
let positioned = PositionedPages::new(
pages,
Margins::trbl(
model.margins.top,
@@ -2206,13 +2344,15 @@ pub(super) fn render_pdf(
cjk_family,
mono_family,
sans_family,
));
);
let links = positioned.link_annotations(document.font_cache(), model.page.height_mm);
document.push(positioned);
let mut pdf = Vec::new();
document
.render(&mut pdf)
.map_err(|error| format!("Rust PDF layout failed: {error}"))?;
super::log_timing("pdf.paint", timing_start);
return Ok(pdf);
return add_link_annotations(pdf, &links);
}
let RenderResources {
mut document,
@@ -3144,3 +3284,72 @@ fn graphic_dimension(value: &str, reference_mm: f64) -> Option<f64> {
}
parse_dimension(value)
}
/// Add clickable `/Link` annotations to the PDF without depending on a
/// printpdf annotation API. `printpdf 0.3.4` exposes no `/Annots` writer, so the
/// finished file is reopened with lopdf and each page dictionary is extended.
fn add_link_annotations(pdf: Vec<u8>, links: &[LinkAnnotation]) -> Result<Vec<u8>, String> {
if links.is_empty() {
return Ok(pdf);
}
let mut document = lopdf::Document::load_mem(&pdf)
.map_err(|error| format!("reopen PDF for links: {error}"))?;
let pages = document.get_pages();
let mut by_page: std::collections::BTreeMap<u32, Vec<&LinkAnnotation>> =
std::collections::BTreeMap::new();
for link in links {
by_page.entry(link.page).or_default().push(link);
}
for (page_number, page_links) in by_page {
let Some(page_id) = pages.get(&page_number).copied() else {
continue;
};
let mut annotation_ids = Vec::with_capacity(page_links.len());
for link in page_links {
let mut action = lopdf::Dictionary::new();
action.set("S", lopdf::Object::Name(b"URI".to_vec()));
action.set("URI", lopdf::Object::string_literal(link.url.clone()));
let mut dictionary = lopdf::Dictionary::new();
dictionary.set("Type", lopdf::Object::Name(b"Annot".to_vec()));
dictionary.set("Subtype", lopdf::Object::Name(b"Link".to_vec()));
dictionary.set(
"Rect",
lopdf::Object::Array(
link.rect
.iter()
.map(|value| lopdf::Object::Real(*value))
.collect(),
),
);
dictionary.set(
"Border",
lopdf::Object::Array(vec![
lopdf::Object::Integer(0),
lopdf::Object::Integer(0),
lopdf::Object::Integer(0),
]),
);
dictionary.set("A", lopdf::Object::Dictionary(action));
annotation_ids.push(document.add_object(dictionary));
}
let page = document
.get_object_mut(page_id)
.map_err(|error| format!("read PDF page: {error}"))?;
let dictionary = page
.as_dict_mut()
.map_err(|error| format!("read PDF page dictionary: {error}"))?;
let mut annots = match dictionary.get(b"Annots") {
Ok(lopdf::Object::Array(array)) => array.clone(),
_ => Vec::new(),
};
for id in annotation_ids {
annots.push(lopdf::Object::Reference(id));
}
dictionary.set("Annots", lopdf::Object::Array(annots));
}
let mut output = Vec::new();
document
.save_to(&mut output)
.map_err(|error| format!("write PDF links: {error}"))?;
Ok(output)
}