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

Generated
+1
View File
@@ -948,6 +948,7 @@ dependencies = [
"genpdf",
"hyphenate",
"image",
"lopdf",
"printpdf",
"rmp-serde",
"rusttype",
+1
View File
@@ -19,6 +19,7 @@ flate2 = "1.1"
hyphenate = { path = "vendor/hyphenate" }
genpdf = { version = "0.2.0", features = ["images"] }
printpdf = "0.3.4"
lopdf = "0.26"
image = { version = "0.23.12", default-features = false, features = ["png", "jpeg", "bmp"] }
common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0", features = ["serde"] }
boxworks = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
+3 -2
View File
@@ -364,8 +364,9 @@ are not implemented. These LaTeX command
definitions support up to nine parameters, including one optional first
parameter with a default value. Unknown packages fail with a clear error. Hyperlinks (`\href`, `\url`, and
resolved citations) use hyperref's green link colour; `\orcidlink{id}`
renders a green `iD` badge linked to `orcid.org`. PDF link annotations are
not emitted.
renders a green `iD` badge linked to `orcid.org`. Visible `\url` text also
emits a real PDF `/Link` URI annotation; `\href` and ORCID-name links still
need their target URL carried through the document model.
`\includegraphics` embeds PNG, JPEG, or BMP files relative to the `.tex` file.
It supports `width`, `height`, and `scale`; width and height accept physical
+10 -7
View File
@@ -110,11 +110,14 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- Preprint title blocks: ORCID links in `\author` render as a native vector
badge (ORCID green square with a white iD) before the author name; the
original bitmap ORCID logo is not embedded.
Hyperlinks use hyperref's green text colour; PDF link annotations are not
emitted. Metadata baselines match the reference within 0.3 pt and page 1 keeps the same closing section-2 line as the reference. PDF link annotations are
blocked on `printpdf 0.3.4`: it has no annotation API, so a vendored printpdf
patch must add a `/Annots` writer before `\href`/ORCID links can be clickable.
The same patch is the natural place to attach API-provided ORCID icon images.
Hyperlinks use hyperref's green text colour; visible `\url` text emits a
PDF `/Link` URI annotation (`/Annots`). `\href`/ORCID-name labels still
carry only colour, because their target URL is not yet stored on the run.
Metadata baselines match the reference within 0.3 pt and page 1 keeps the
same closing section-2 line as the reference. `printpdf 0.3.4` has no
annotation API, so the link is added by reopening the finished PDF with
lopdf and extending each page dictionary. Extending this to `\href`/ORCID
labels (and API-provided ORCID icon images) is the next step.
## Verification
@@ -124,7 +127,7 @@ See `docs/ROADMAP.md` for concrete implementation plans.
3.6 MB and `pdffonts` reports only embedded CID TrueType faces); this avoids
viewer-dependent glyph substitution. Tables use natural column widths and
centered rules; preview and PDF share the same table line coordinates.
- `cargo fmt --check` passes; `cargo test --offline` (53 tests: 49 compiler
- `cargo fmt --check` passes; `cargo test --offline` (54 tests: 50 compiler
integration tests + 4 server tests) covers the three examples, the arXiv
fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output,
project API, static frontend assets, path traversal, the legacy
@@ -133,7 +136,7 @@ See `docs/ROADMAP.md` for concrete implementation plans.
## Verification snapshot
- Compiler integration tests: 49; server tests: 4; total 53.
- Compiler integration tests: 50; server tests: 4; total 54.
- `cargo fmt --check` passes.
- arXiv fixture: 3 Letter pages, ~3.6 MB, embedded Liberation faces only.
- Title/author/date/Introduction baselines within 0.3 pt of the XeLaTeX
+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)
}
+20
View File
@@ -1550,3 +1550,23 @@ After text.
"caption footnote should be painted on the figure page"
);
}
#[test]
fn url_text_creates_a_pdf_link_annotation() {
let source = r"\documentclass{article}
\begin{document}
Visit \url{https://example.com/docs/page} for details.
\end{document}";
let pdf = CompilerSession::default()
.compile(source, "url-link.tex")
.expect("URL PDF");
let text = String::from_utf8_lossy(&pdf);
assert!(
text.contains("/Subtype/Link"),
"URL text should produce a link annotation"
);
assert!(
text.contains("https://example.com/docs/page"),
"annotation should carry the full URL"
);
}