Annotate href labels with PDF link targets

This commit is contained in:
gloamxun committed 2026-10-19 21:33:26 +08:00
1 parent 88646c9453
commit 05d7980561
7 files changed
+68 -35

No files matched your search

+3
View File
@@ -99,6 +99,8 @@ pub struct DocumentModel {
pub labels: HashMap<String, String>,
pub citations: HashMap<String, usize>,
pub citation_metadata: HashMap<String, CitationMetadata>,
/// Display text -> hyperlink URL for `\href` annotations.
pub link_targets: HashMap<String, String>,
/// Bibliography keys in the order their metadata was declared. Needed to
/// assign natbib-style year suffixes (2014a, 2014b, ...) deterministically.
pub bibliography_order: Vec<String>,
@@ -128,6 +130,7 @@ impl Default for DocumentModel {
labels: HashMap::new(),
citations: HashMap::new(),
citation_metadata: HashMap::new(),
link_targets: HashMap::new(),
bibliography_order: Vec::new(),
author_year_citations: false,
footnotes: Vec::new(),
@@ -1155,6 +1155,9 @@ impl Parser {
expanded::FrontendEventKind::LinkStart => {
self.link_depth = self.link_depth.saturating_add(1);
}
expanded::FrontendEventKind::LinkTarget { text, url } => {
self.document.link_targets.insert(text.clone(), url.clone());
}
expanded::FrontendEventKind::LinkEnd => {
self.link_depth = self.link_depth.saturating_sub(1);
}
+5
View File
@@ -266,6 +266,11 @@ pub enum FrontendEventKind {
PageNumber,
/// Start of hyperlink material.
LinkStart,
/// `\href` target: display text and URL, used for PDF annotations.
LinkTarget {
text: String,
url: String,
},
/// End of hyperlink material.
LinkEnd,
/// A package or class was loaded from a local file.
+1 -32
View File
@@ -1,35 +1,4 @@
\documentclass{article}
\begin{document}
\section*{Compatibility examples}
Spacing: A\quad B\qquad C, A\thinspace B\enspace C.
Symbols: \S\P\dag\ddag\copyright\textbullet\textregistered\texttrademark
\ldots\textendash\textemdash\guillemotleft x\guillemotright
\texteuro\textsterling\textyen\textdegree\textpm.
Letters: \ss\ae\AE\oe\OE\aa\AA\o\O\l\L\i.
Styles: {\bfseries bold}, {\itshape italic}, {\ttfamily mono}, \textsc{small caps}.
Breaks: A\nopagebreak[4] B\linebreak[2] C\samepage.
A\vspace*{6pt} B
\vspace{6pt}
A\hspace*{1cm}B
\begin{center}
Centered text
\end{center}
\hrule
\fbox{Framed box} and \mbox{unbreakable box}.
\parbox{60mm}{A parbox wraps its content to sixty millimetres and stays
in the vertical flow.}
See \href{https://example.com/target}{Click here} now.
\end{document}
+28 -3
View File
@@ -537,6 +537,7 @@ impl PositionedPages {
&self,
fonts: &fonts::FontCache,
page_height_mm: f64,
link_targets: &HashMap<String, String>,
) -> Vec<LinkAnnotation> {
let mut annotations = Vec::new();
for (index, page) in self.pages.iter().enumerate() {
@@ -576,6 +577,7 @@ impl PositionedPages {
*font_size,
index as u32 + 1,
page_height_mm,
link_targets,
);
}
PositionedPageItem::Centered { element, y, .. } => {
@@ -601,6 +603,7 @@ impl PositionedPages {
font_size,
index as u32 + 1,
page_height_mm,
link_targets,
);
line_y += em * 1.2;
}
@@ -622,6 +625,7 @@ fn push_url_annotations(
font_size: u8,
page: u32,
page_height_mm: f64,
link_targets: &HashMap<String, String>,
) {
let mut fragments: Vec<(String, f64, f64)> = Vec::new();
let em = f64::from(font_size) * 25.4 / 72.27;
@@ -629,11 +633,24 @@ fn push_url_annotations(
if fragments.is_empty() {
return;
}
let url = fragments
let text = fragments
.iter()
.map(|(text, _, _)| text.as_str())
.collect::<String>();
if url.starts_with("http://") || url.starts_with("https://") {
let spaced = fragments
.iter()
.map(|(text, _, _)| text.as_str())
.collect::<Vec<_>>()
.join(" ");
let url = if text.starts_with("http://") || text.starts_with("https://") {
Some(text.clone())
} else {
link_targets
.get(&spaced)
.or_else(|| link_targets.get(&text))
.cloned()
};
if let Some(url) = url {
for (_, x, width) in fragments.iter() {
let left = line_x_mm + *x;
annotations.push(LinkAnnotation {
@@ -652,6 +669,10 @@ fn push_url_annotations(
};
for span in &layout.spans {
if !span.link {
if !fragments.is_empty() && span.text.chars().all(char::is_whitespace) {
fragments.push((" ".to_string(), f64::from(span.x), 0.0));
continue;
}
flush(&mut fragments, annotations);
continue;
}
@@ -2346,7 +2367,11 @@ pub(super) fn render_pdf(
mono_family,
sans_family,
);
let links = positioned.link_annotations(document.font_cache(), model.page.height_mm);
let links = positioned.link_annotations(
document.font_cache(),
model.page.height_mm,
&model.link_targets,
);
document.push(positioned);
let mut pdf = Vec::new();
document
+8
View File
@@ -3664,6 +3664,14 @@ fn href_primitive(
let url = read_unexpanded_argument(input, token, "expects a link URL")?;
let content = read_unexpanded_argument(input, token, "expects link text")?;
let inner = strip_braced_tokens(&content).to_vec();
write_event(
input,
token,
FrontendEventKind::LinkTarget {
text: simple_token_text(&content).trim().to_string(),
url: simple_token_text(&url).trim().to_string(),
},
);
write_event(input, token, FrontendEventKind::LinkStart);
let trace_key = token.trace_key();
let mut expansion = Vec::new();
+20
View File
@@ -1551,6 +1551,26 @@ After text.
);
}
#[test]
fn href_text_creates_a_pdf_link_annotation() {
let source = r"\documentclass{article}
\begin{document}
See \href{https://example.com/target}{Click here} now.
\end{document}";
let pdf = CompilerSession::default()
.compile(source, "href-link.tex")
.expect("href PDF");
let text = String::from_utf8_lossy(&pdf);
assert!(
text.contains("/Subtype/Link"),
"href text should be clickable"
);
assert!(
text.contains("https://example.com/target"),
"annotation should carry the href target"
);
}
#[test]
fn url_text_creates_a_pdf_link_annotation() {
let source = r"\documentclass{article}