Emit PDF link annotations from display lists

This commit is contained in:
gloamxun committed 2026-10-20 18:14:47 +08:00
1 parent 431bbd14d4
commit da7f580bf0
4 files changed
+103 -2

No files matched your search

+45 -1
View File
@@ -69,6 +69,7 @@ fn page_content(list: &DisplayList, height: i64, image_names: &BTreeMap<usize, S
));
}
}
DisplayItem::Link { .. } => {}
}
}
content.push_str("Q\n");
@@ -113,10 +114,38 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8>
} else {
format!("<< /Font << /F1 3 0 R >> /XObject << {xobjects} >> >>")
};
let links = list
.items
.iter()
.filter_map(|item| match item {
DisplayItem::Link {
x,
y,
width,
height,
url,
} => Some((*x, *y, *width, *height, url.clone())),
_ => None,
})
.collect::<Vec<_>>();
let annotation_base = image_base + used.len();
let annots = if links.is_empty() {
String::new()
} else {
let refs = (0..links.len())
.map(|index| {
format!("/Annots [{}]", (annotation_base + index))
.replace("/Annots [", "")
.replacen("]", "", 1)
})
.collect::<Vec<_>>()
.join(" ");
format!(" /Annots [{refs}]")
};
kids.push(format!("{page_id} 0 R"));
objects.push(
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources {resources} /Contents {content_id} 0 R >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources {resources}{annots} /Contents {content_id} 0 R >>",
pt(width),
pt(height)
)
@@ -150,6 +179,21 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8>
object.extend_from_slice(b"\nendstream");
objects.push(object);
}
for (index, (x, y, width, link_height, url)) in links.iter().enumerate() {
let _ = index;
objects.push(
format!(
"<< /Type /Annot /Subtype /Link /Rect [{:.3} {:.3} {:.3} {:.3}] /Border [0 0 0] /A << /S /URI /URI ({}) >> >>",
*x as f64 / 65_536.0,
(height as f64 - *y as f64 - *link_height as f64) / 65_536.0,
(*x + *width) as f64 / 65_536.0,
(height as f64 - *y as f64) / 65_536.0,
escape(url)
)
.into_bytes(),
);
}
}
objects[1] = format!(
"<< /Type /Pages /Kids [{}] /Count {} >>",