Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat(pdf): preserve clickable links and internal destinations

ldm05be5f7c50d7f
diff --git a/moli-dom/src/native/host/document.rs b/moli-dom/src/native/host/document.rs
index 6b20b7330..c687626a1 100644
--- a/moli-dom/src/native/host/document.rs
+++ b/moli-dom/src/native/host/document.rs
@@ -1375,7 +1375,12 @@ impl DomHost {
self.find_document_anchor(document_handle, &decoded)
}
- fn find_document_anchor(&self, document_handle: DomHandle, name: &str) -> Option<DomHandle> {
+ /// Finds an ID or legacy named anchor without changing the document target.
+ pub fn find_document_anchor(
+ &self,
+ document_handle: DomHandle,
+ name: &str,
+ ) -> Option<DomHandle> {
if name.is_empty() || !self.node(document_handle).is_some_and(Node::is_document) {
return None;
}
diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rs
index 0a5c67218..7c1aa8bf4 100644
--- a/moli-layout/src/lib.rs
+++ b/moli-layout/src/lib.rs
@@ -80,19 +80,19 @@ pub use snapshot::{
PaintFontId, PaintFontResource, PaintFragment, PaintGlyph, PaintGlyphRun,
PaintGradientColorSpace, PaintGradientExtend, PaintGradientHueDirection,
PaintGradientInterpolation, PaintGradientStop, PaintImage, PaintImageId, PaintImageResource,
- PaintImageSampling, PaintLineCap, PaintLineJoin, PaintLinearGradient, PaintPath,
- PaintPathElement, PaintPoint, PaintRadialGradient, PaintRect, PaintShape, PaintSize,
- PaintSnapshot, PaintStroke, PaintSvgImage, PaintSvgImageId, PaintSvgImageResource,
- PaintTextDecoration, PaintTextDecorationStyle, PaintTextSemantics, PaintTextShadow,
- PaintTransform2D, PaintViewport, pixel_snap_paint_axis, pixel_snap_paint_axis_allowing_zero,
- pixel_snap_paint_rect,
+ PaintImageSampling, PaintLineCap, PaintLineJoin, PaintLinearGradient, PaintLink,
+ PaintLinkTarget, PaintPath, PaintPathElement, PaintPoint, PaintRadialGradient, PaintRect,
+ PaintShape, PaintSize, PaintSnapshot, PaintStroke, PaintSvgImage, PaintSvgImageId,
+ PaintSvgImageResource, PaintTextDecoration, PaintTextDecorationStyle, PaintTextSemantics,
+ PaintTextShadow, PaintTransform2D, PaintViewport, pixel_snap_paint_axis,
+ pixel_snap_paint_axis_allowing_zero, pixel_snap_paint_rect,
};
pub use source::{
LayoutElementCategory, LayoutElementMetadata, LayoutElementSemantics, LayoutFormControlData,
- LayoutFormControlKind, LayoutImageResource, LayoutInputControlKind, LayoutListData,
- LayoutListRole, LayoutNamespace, LayoutPseudo, LayoutReplacedKind, LayoutSource,
- LayoutSourceKind, LayoutStyleResolver, LayoutTableData, LayoutTableRole, LayoutTextSelection,
- ReplacedMetrics, ResolvedLayoutElementStyles, ResolvedLayoutPseudoStyle,
+ LayoutFormControlKind, LayoutHyperlink, LayoutImageResource, LayoutInputControlKind,
+ LayoutListData, LayoutListRole, LayoutNamespace, LayoutPseudo, LayoutReplacedKind,
+ LayoutSource, LayoutSourceKind, LayoutStyleResolver, LayoutTableData, LayoutTableRole,
+ LayoutTextSelection, ReplacedMetrics, ResolvedLayoutElementStyles, ResolvedLayoutPseudoStyle,
};
pub use style::{
LayoutDisplay, LayoutInlineAlignment, LayoutListMarkerPosition, LayoutListMarkerType,
diff --git a/moli-layout/src/paint/links.rs b/moli-layout/src/paint/links.rs
new file mode 100644
index 000000000..af04ed159
--- /dev/null
+++ b/moli-layout/src/paint/links.rs
@@ -0,0 +1,109 @@
+//! Print-only projection of flat-tree links onto the existing box/line fragments.
+use std::{collections::HashMap, fmt::Debug, hash::Hash};
+
+use crate::{
+ LayoutFragmentId, LayoutFragmentKind, LayoutPoint, LayoutSource, PaintLink, PaintLinkTarget,
+ PaintSnapshot, projection::OutputProjection,
+};
+
+pub(super) struct LinkProjection {
+ targets: Vec<Option<PaintLinkTarget>>,
+}
+
+impl LinkProjection {
+ pub(super) fn new<N, S>(projection: &OutputProjection<'_, N>, source: &S) -> Self
+ where
+ N: Copy + Debug + Eq + Hash,
+ S: LayoutSource<NodeId = N>,
+ {
+ let mut cache: HashMap<N, Option<PaintLinkTarget>> = HashMap::new();
+ let targets = projection
+ .world
+ .boxes
+ .iter()
+ .map(|layout_box| {
+ let mut current = layout_box.source.or(layout_box.owner);
+ let mut ancestors = Vec::new();
+ let mut target = None;
+ while let Some(node) = current {
+ if let Some(cached) = cache.get(&node) {
+ target = cached.clone();
+ break;
+ }
+ ancestors.push(node);
+ if let Some(link) = source.hyperlink(node) {
+ let destination = link.destination.and_then(|node| {
+ let id = projection.world.source_box(node).or_else(|| {
+ projection
+ .world
+ .display_contents_mapping
+ .get(&node)?
+ .first()
+ .copied()
+ })?;
+ let fragment = projection.boxes[id.index()].fragments.first()?;
+ let fragment = &projection.fragments[fragment.index()];
+ let matrix = projection.coordinate_spaces
+ [fragment.coordinate_space.index()]
+ .paint
+ .local_transform();
+ Some(
+ matrix
+ .map_point(LayoutPoint::new(fragment.rect.x, fragment.rect.y)),
+ )
+ });
+ target = Some(PaintLinkTarget {
+ url: link.url,
+ destination,
+ });
+ break;
+ }
+ current = source.flat_parent(node);
+ }
+ for node in ancestors {
+ cache.insert(node, target.clone());
+ }
+ target
+ })
+ .collect();
+ Self { targets }
+ }
+
+ pub(super) fn append<N>(
+ &self,
+ projection: &OutputProjection<'_, N>,
+ fragment: LayoutFragmentId,
+ snapshot: &mut PaintSnapshot,
+ ) where
+ N: Copy + Debug + Eq + Hash,
+ {
+ let fragment = &projection.fragments[fragment.index()];
+ let box_id = match fragment.kind {
+ LayoutFragmentKind::Box { box_id }
+ | LayoutFragmentKind::InlineBox { box_id, .. }
+ | LayoutFragmentKind::Text { box_id, .. } => box_id,
+ LayoutFragmentKind::Line { .. } => return,
+ };
+ if !projection.world.boxes[box_id.index()].style.is_visible()
+ || fragment.rect.width <= 0.0
+ || fragment.rect.height <= 0.0
+ {
+ return;
+ }
+ let Some(mut target) = self.targets[box_id.index()].clone() else {
+ return;
+ };
+ target.destination = target
+ .destination
+ .map(|p| snapshot.viewport_to_surface.map_point(p));
+ let matrix = projection.coordinate_spaces[fragment.coordinate_space.index()]
+ .paint
+ .local_transform();
+ snapshot.links.push(PaintLink {
+ before_fragment: snapshot.fragments.len(),
+ rect: fragment.rect,
+ transform: snapshot.viewport_to_surface.concatenate(matrix),
+ target,
+ });
+ }
+}
diff --git a/moli-layout/src/paint/mod.rs b/moli-layout/src/paint/mod.rs
index d9a0b0fc7..2ef06b3cf 100644
--- a/moli-layout/src/paint/mod.rs
+++ b/moli-layout/src/paint/mod.rs
@@ -6,6 +6,7 @@ mod form_controls;
mod geometry;
mod image;
mod inline_boxes;
+mod links;
mod mask;
mod scrollbar;
mod table;
@@ -128,8 +129,9 @@ enum UnavailableReplacedContentPaint {
TransparentCanvas,
}
-pub(crate) fn project_paint_snapshot<N>(
+pub(crate) fn project_paint_snapshot<N, S: crate::LayoutSource<NodeId = N>>(
projection: &OutputProjection<'_, N>,
+ source: &S,
capture: ResolvedPaintCapture,
retain_text_semantics: bool,
embedded_frames: &mut HashMap<LayoutBoxId, PaintSnapshot>,
@@ -149,6 +151,7 @@ where
snapshot.viewport_to_surface = capture.viewport_to_surface;
snapshot.content_size = projection.document_content_size();
snapshot.diagnostics = projection.diagnostics.clone();
+ let links = retain_text_semantics.then(|| links::LinkProjection::new(projection, source));
let cull_plan = PaintCullPlan::build(projection);
let mut metrics = PaintProjectionMetrics {
event_count: projection.paint_events.len(),
@@ -371,6 +374,11 @@ where
projection.background_clips[id.index()],
&mut snapshot,
);
+ if let Some(links) = &links
+ && let Some(fragment) = projection.direct_fragments[id.index()]
+ {
+ links.append(projection, fragment, &mut snapshot);
+ }
project_box_background(
projection,
id,
@@ -388,6 +396,11 @@ where
projection.content_clips[id.index()],
&mut snapshot,
);
+ if let Some(links) = &links {
+ for fragment in &projection.owner_paint_fragments[id.index()] {
+ links.append(projection, *fragment, &mut snapshot);
+ }
+ }
project_box_contents(
projection,
id,
diff --git a/moli-layout/src/pass.rs b/moli-layout/src/pass.rs
index 4a7ad15e3..35299ee28 100644
--- a/moli-layout/src/pass.rs
+++ b/moli-layout/src/pass.rs
@@ -277,7 +277,7 @@ where
let embedded_frame_elapsed = phase_started.elapsed();
finish_layout_pass(
&world,
- source.root(),
+ source,
request.viewport,
request.reason,
started,
diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rs
index a5244c87c..121841780 100644
--- a/moli-layout/src/projection.rs
+++ b/moli-layout/src/projection.rs
@@ -32,9 +32,9 @@ pub(crate) struct LayoutPassPhaseMetrics {
pub(crate) numeric_feedback_overflow_recomputed_node_count: usize,
}
-pub(crate) fn finish_layout_pass<N>(
+pub(crate) fn finish_layout_pass<N, S: crate::LayoutSource<NodeId = N>>(
world: &LayoutWorld<N>,
- source_root: N,
+ source: &S,
viewport: LayoutViewport,
reason: LayoutFlushReason,
started: Instant,
@@ -71,6 +71,7 @@ where
.map(|capture| {
crate::paint::project_paint_snapshot(
&projection,
+ source,
capture,
reason == LayoutFlushReason::Print,
&mut embedded_paint,
@@ -139,7 +140,7 @@ where
tree: Box::new(snapshot.tree),
})
.collect();
- let tree = projection.into_frozen_tree(source_root, content_size, embedded_frames);
+ let tree = projection.into_frozen_tree(source.root(), content_size, embedded_frames);
Ok(LayoutPassResult::new(
tree,
diagnostics,
@@ -227,7 +228,7 @@ where
box_sources: Vec<Option<N>>,
principal_sources: Vec<Option<N>>,
hit_sources: Vec<Option<N>>,
- fragments: Vec<LayoutFragment>,
+ pub(crate) fragments: Vec<LayoutFragment>,
scroll_proxy_links: Vec<(N, LayoutOutputBoxId)>,
pub(crate) scroll_extents: Vec<LayoutScrollExtent>,
pub(crate) coordinate_spaces: Vec<ProjectedCoordinateSpace>,
@@ -238,8 +239,8 @@ where
resolved_transforms: Vec<ResolvedLayoutTransform>,
scrollable_overflow: Vec<LayoutRect>,
viewport_anchored: Vec<bool>,
- direct_fragments: Vec<Option<LayoutFragmentId>>,
- owner_paint_fragments: Vec<Vec<LayoutFragmentId>>,
+ pub(crate) direct_fragments: Vec<Option<LayoutFragmentId>>,
+ pub(crate) owner_paint_fragments: Vec<Vec<LayoutFragmentId>>,
pub(crate) background_clips: Vec<Option<LayoutClipChainId>>,
pub(crate) content_clips: Vec<Option<LayoutClipChainId>>,
pub(crate) paint_events: Vec<PaintOrderEvent>,
diff --git a/moli-layout/src/snapshot.rs b/moli-layout/src/snapshot.rs
index 80c99641e..e09c72958 100644
--- a/moli-layout/src/snapshot.rs
+++ b/moli-layout/src/snapshot.rs
@@ -880,6 +880,25 @@ impl PaintDiagnostic {
}
}
+/// An owned hyperlink region in the coordinate system of its paint scope.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PaintLink {
+ /// Scopes active immediately before this paint command also clip the link.
+ /// May equal `fragments.len()` (before closing an embedded snapshot).
+ pub before_fragment: usize,
+ pub rect: PaintRect,
+ pub transform: PaintTransform2D,
+ pub target: PaintLinkTarget,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct PaintLinkTarget {
+ /// Absolute URL; also the fallback if an internal destination is not printed.
+ pub url: std::sync::Arc<str>,
+ /// Same-document destination in capture-surface CSS pixels.
+ pub destination: Option<PaintPoint>,
+}
+
/// Fully owned input to a paint backend.
///
/// No source-tree identifier, computed-style handle, or renderer borrow is
@@ -904,6 +923,8 @@ pub struct PaintSnapshot {
pub content_size: PaintSize,
/// Paint operations in back-to-front order.
pub fragments: Vec<PaintFragment>,
+ /// Print-only hyperlinks. No DOM handles or live layout borrows are retained.
+ pub links: Vec<PaintLink>,
/// Immutable resources referenced by glyph fragments.
pub fonts: Vec<PaintFontResource>,
/// Immutable resources referenced by image fragments.
@@ -925,6 +946,7 @@ impl PaintSnapshot {
canvas_color,
content_size: PaintSize::new(viewport.css_width as f32, viewport.css_height as f32),
fragments: Vec::new(),
+ links: Vec::new(),
fonts: Vec::new(),
images: Vec::new(),
svg_images: Vec::new(),
@@ -1041,7 +1063,12 @@ impl PaintSnapshot {
transform: local_to_surface,
});
}
+ let mut fragment_offsets =
+ (!child.links.is_empty()).then(|| Vec::with_capacity(child.fragments.len() + 1));
for fragment in child.fragments {
+ if let Some(offsets) = &mut fragment_offsets {
+ offsets.push(self.fragments.len());
+ }
if let Some(fragment) = rebase_embedded_fragment(
fragment,
local_to_surface,
@@ -1052,6 +1079,23 @@ impl PaintSnapshot {
self.push_fragment(fragment);
}
}
+ if let Some(offsets) = &mut fragment_offsets {
+ offsets.push(self.fragments.len());
+ }
+ for mut link in child.links {
+ // Do not turn malformed child metadata into a valid parent index.
+ link.before_fragment = fragment_offsets
+ .as_ref()
+ .and_then(|offsets| offsets.get(link.before_fragment))
+ .copied()
+ .unwrap_or(usize::MAX);
+ link.transform = local_to_surface.concatenate(link.transform);
+ link.target.destination = link
+ .target
+ .destination
+ .map(|point| local_to_surface.map_point(point));
+ self.links.push(link);
+ }
self.push_fragment(PaintFragment::PopLayer);
for diagnostic in child.diagnostics {
if !self.diagnostics.contains(&diagnostic) {
diff --git a/moli-layout/src/source.rs b/moli-layout/src/source.rs
index d68813901..7580b77c4 100644
--- a/moli-layout/src/source.rs
+++ b/moli-layout/src/source.rs
@@ -486,6 +486,14 @@ impl LayoutTextSelection {
}
}
+/// A resolved hyperlink, sampled only for document export. A same-document
+/// destination retains source identity only until paint projection finishes.
+#[derive(Clone, Debug)]
+pub struct LayoutHyperlink<N> {
+ pub url: std::sync::Arc<str>,
+ pub destination: Option<N>,
+}
+
/// A short-lived, read-only view of the renderer's canonical flat tree.
pub trait LayoutSource {
type NodeId: Copy + Debug + Eq + Hash;
@@ -526,6 +534,12 @@ pub trait LayoutSource {
fn text(&self, node: Self::NodeId) -> Option<&str>;
fn label(&self, node: Self::NodeId) -> String;
+ /// Returns a link owned by this element, with its URL resolved against the
+ /// document base. Ancestor links are handled by the export projection.
+ fn hyperlink(&self, _node: Self::NodeId) -> Option<LayoutHyperlink<Self::NodeId>> {
+ None
+ }
+
/// Returns the active document selection intersecting one source text node.
fn text_selection(&self, _node: Self::NodeId) -> Option<LayoutTextSelection> {
None
diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rs
index fc1e7ae1f..4de0418e7 100644
--- a/moli-layout/tests/phase5_output_contract.rs
+++ b/moli-layout/tests/phase5_output_contract.rs
@@ -104,6 +104,13 @@ impl LayoutSource for Source {
self.0[node].label.to_owned()
}
+ fn hyperlink(&self, node: usize) -> Option<moli_layout::LayoutHyperlink<usize>> {
+ (self.0[node].local_name == "a").then(|| moli_layout::LayoutHyperlink {
+ url: self.0[node].label.into(),
+ destination: None,
+ })
+ }
+
fn scroll_offset(&self, node: Self::NodeId) -> LayoutPoint {
self.0[node].scroll
}
@@ -150,6 +157,48 @@ fn build(source: &Source, styles: &mut Styles) -> LayoutPassResult<usize> {
)
}
+#[test]
+fn owned_links_are_collected_only_for_printing_and_do_not_change_paint() {
+ let (raster, print) = {
+ let source = Source(vec![
+ Node::element("root", vec![1]),
+ Node::html_element("https://example.com/link", "a", vec![2]),
+ Node::element("child", vec![]),
+ ]);
+ let mut styles = Styles(HashMap::from([
+ (0, fixed_size(LayoutDisplay::Block, 320.0, 240.0)),
+ (1, fixed_size(LayoutDisplay::Block, 100.0, 40.0)),
+ (2, fixed_size(LayoutDisplay::Block, 30.0, 20.0)),
+ ]));
+ let viewport = LayoutViewport::new(320, 240, 1.0);
+ let raster = build_with_request(
+ &source,
+ &mut styles,
+ LayoutPassRequest::with_paint(viewport, LayoutFlushReason::Test),
+ )
+ .into_paint_snapshot()
+ .unwrap();
+ let print = build_with_request(
+ &source,
+ &mut styles,
+ LayoutPassRequest::with_paint(viewport, LayoutFlushReason::Print),
+ )
+ .into_paint_snapshot()
+ .unwrap();
+ (raster, print)
+ };
+ assert!(raster.links.is_empty());
+ assert_eq!(raster.fragments, print.fragments);
+ assert_eq!(print.links.len(), 2, "anchor and inherited child regions");
+ assert!(
+ print
+ .links
+ .iter()
+ .all(|link| link.target.url.as_ref() == "https://example.com/link")
+ );
+ assert_eq!(print.links[0].rect.width, 100.0);
+}
+
fn build_with_request(
source: &Source,
styles: &mut Styles,
diff --git a/moli-paint/README.md b/moli-paint/README.md
index 36db6b79c..d8e91486f 100644
--- a/moli-paint/README.md
+++ b/moli-paint/README.md
@@ -65,7 +65,13 @@ replayed slices from duplicating the extracted document. Device pixel ratio does
not affect PDF page geometry. Page ranges still refer to original document pages.
This does not implement CSS fragmentation (`break-inside`, repeated table headers,
-`@page`), tagged PDF, link annotations or document outlines. PDF reading order still
+`@page`), tagged PDF or document outlines. HTML anchor links are retained as PDF
+annotations, including resolved relative URLs, wrapped lines, transforms, overflow
+and clip-path clipping, embedded frames and page boundaries. Same-document IDs and
+legacy named anchors become PDF destinations; omitted destination pages fall back
+to the original URL. Curved clip boundaries use half-CSS-pixel strips; rectangular
+and transformed rectangular clips use polygon intersections. JavaScript handlers,
+image maps and links inside SVG resources are not exported. PDF reading order still
follows paint order, and complex-script extraction depends on the reader's handling
of ToUnicode/ActualText. SVG text that takes a raster fallback has no separate text
mapping. This is not an accessibility or PDF/UA implementation. Krilla
diff --git a/moli-paint/src/pdf/links.rs b/moli-paint/src/pdf/links.rs
new file mode 100644
index 000000000..602a912cd
--- /dev/null
+++ b/moli-paint/src/pdf/links.rs
@@ -0,0 +1,351 @@
+//! PDF annotations do not inherit content-stream clips or transforms. Project
+//! their hit regions explicitly before encoding them, including page slicing.
+use std::collections::BTreeMap;
+
+use krilla::{
+ action::{Action, LinkAction},
+ annotation::{LinkAnnotation, Target},
+ destination::{Destination, XyzDestination},
+ geom::{Point as PdfPoint, Quadrilateral},
+ page::Page,
+};
+use moli_layout::{PaintFilter, PaintFragment, PaintLinkTarget, PaintShape, PaintSnapshot};
+use peniko::kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape};
+
+use super::{PdfError, PdfOptions};
+
+type Polygon = Vec<Point>;
+pub(super) struct LinkRegion {
+ polygon: Polygon,
+ target: PaintLinkTarget,
+}
+
+enum Clip {
+ Rectangle(Polygon),
+ Path(Vec<(Point, Point)>, Rect),
+}
+
+struct Scope {
+ clip: Clip,
+ hidden: bool,
+}
+
+fn spend(budget: &mut usize, count: usize) -> Result<(), PdfError> {
+ *budget = budget.checked_sub(count).ok_or(PdfError::ResourceLimit)?;
+ Ok(())
+}
+
+pub(super) fn collect(snapshot: &PaintSnapshot) -> Result<Vec<LinkRegion>, PdfError> {
+ if snapshot.links.is_empty() {
+ return Ok(Vec::new());
+ }
+ let mut links = snapshot.links.iter().collect::<Vec<_>>();
+ links.sort_by_key(|link| link.before_fragment);
+ let mut links = links.into_iter().peekable();
+ let mut scopes: Vec<Scope> = Vec::new();
+ let mut regions: Vec<LinkRegion> = Vec::new();
+ let mut budget = 20_000_000;
+ let capture = Rect::new(
+ 0.0,
+ 0.0,
+ snapshot.surface.css_width.into(),
+ snapshot.surface.css_height.into(),
+ );
+ for index in 0..=snapshot.fragments.len() {
+ while let Some(link) = links.next_if(|link| link.before_fragment == index) {
+ if scopes.iter().any(|scope| scope.hidden) {
+ continue;
+ }
+ let matrix = Affine::new(link.transform.coefficients);
+ let polygon = rectangle(matrix, super::rect(link.rect));
+ if polygon
+ .iter()
+ .any(|p| !(p.x as f32).is_finite() || !(p.y as f32).is_finite())
+ {
+ return Err(PdfError::Encoding(
+ "invalid transformed link geometry".into(),
+ ));
+ }
+ let mut polygons = vec![clip_rect(polygon, capture)];
+ for scope in &scopes {
+ let mut clipped = Vec::new();
+ for polygon in polygons {
+ spend(&mut budget, polygon.len())?;
+ match &scope.clip {
+ Clip::Rectangle(clip) => clipped.push(intersect(polygon, clip)),
+ Clip::Path(edges, bounds) => {
+ curved_clip(polygon, edges, *bounds, &mut clipped, &mut budget)?;
+ }
+ }
+ }
+ polygons = clipped;
+ }
+ for polygon in polygons.into_iter().filter(|p| area(p).abs() > 1e-6) {
+ // Inline anchors and their text children often describe the
+ // same region. Remove contained duplicates without joining
+ // separate wrapped lines or filling the gap between them.
+ if regions.iter().rev().take(64).any(|region| {
+ region.target == link.target
+ && polygon.iter().all(|p| contains(&region.polygon, *p))
+ }) {
+ continue;
+ }
+ spend(&mut budget, 100)?;
+ regions.push(LinkRegion {
+ polygon,
+ target: link.target.clone(),
+ });
+ }
+ }
+ let Some(fragment) = snapshot.fragments.get(index) else {
+ break;
+ };
+ let (shape, matrix, hidden) = match fragment {
+ PaintFragment::PushClip { shape, transform } => (shape, transform, false),
+ PaintFragment::PushLayer {
+ clip,
+ transform,
+ opacity,
+ filter,
+ ..
+ } => (
+ clip,
+ transform,
+ *opacity <= 0.0 || matches!(filter, Some(PaintFilter::Opacity(v)) if *v <= 0.0),
+ ),
+ PaintFragment::PopLayer => {
+ scopes.pop();
+ continue;
+ }
+ _ => continue,
+ };
+ let matrix = Affine::new(matrix.coefficients);
+ let clip = match shape {
+ PaintShape::Rect(rect) => Clip::Rectangle(rectangle(matrix, super::rect(*rect))),
+ _ => {
+ let path = matrix * crate::raster::to_backend_shape(shape);
+ let edges = edges(&path);
+ spend(&mut budget, edges.len())?;
+ Clip::Path(edges, path.bounding_box())
+ }
+ };
+ scopes.push(Scope { clip, hidden });
+ }
+ Ok(regions)
+}
+
+pub(super) struct PageLinks<'a> {
+ pub regions: &'a [LinkRegion],
+ pub selected: &'a BTreeMap<usize, usize>,
+ pub page_height: f64,
+ pub scale: f64,
+ pub options: &'a PdfOptions,
+}
+
+impl PageLinks<'_> {
+ pub fn append(&self, page: &mut Page<'_>, source: Rect) -> Result<(), PdfError> {
+ let matrix = Affine::translate((
+ self.options.margin_left,
+ self.options.margin_top - source.y0 * self.scale,
+ )) * Affine::scale(self.scale);
+ for region in self.regions {
+ let polygon = clip_rect(region.polygon.clone(), source);
+ if area(&polygon).abs() <= 1e-6 {
+ continue;
+ }
+ let polygon = polygon.into_iter().map(|p| matrix * p).collect::<Vec<_>>();
+ let mut quads = Vec::new();
+ if polygon.len() == 4 {
+ quads.push(quad([polygon[3], polygon[2], polygon[1], polygon[0]]));
+ } else {
+ for i in 1..polygon.len() - 1 {
+ let a = polygon[0];
+ let b = polygon[i];
+ let c = polygon[i + 1];
+ // Split one triangle edge to provide four distinct points.
+ quads.push(quad([c, b, a.midpoint(b), a]));
+ }
+ }
+ let destination = region.target.destination.and_then(|p| {
+ let original = (f64::from(p.y).max(0.0) / self.page_height).floor() as usize;
+ let output = *self.selected.get(&original)?;
+ let point = PdfPoint::from_xy(
+ (self.options.margin_left + f64::from(p.x) * self.scale) as f32,
+ (self.options.margin_top
+ + (f64::from(p.y).max(0.0) - original as f64 * self.page_height)
+ * self.scale) as f32,
+ );
+ Some(Target::Destination(Destination::Xyz(XyzDestination::new(
+ output, point,
+ ))))
+ });
+ let target = destination.unwrap_or_else(|| {
+ Target::Action(Action::Link(LinkAction::new(region.target.url.to_string())))
+ });
+ page.add_annotation(LinkAnnotation::new_with_quad_points(quads, target).into());
+ }
+ Ok(())
+ }
+}
+
+fn quad(points: [Point; 4]) -> Quadrilateral {
+ Quadrilateral(points.map(|p| PdfPoint::from_xy(p.x as f32, p.y as f32)))
+}
+
+fn rectangle(matrix: Affine, rect: Rect) -> Polygon {
+ let mut points = vec![
+ matrix * Point::new(rect.x0, rect.y0),
+ matrix * Point::new(rect.x1, rect.y0),
+ matrix * Point::new(rect.x1, rect.y1),
+ matrix * Point::new(rect.x0, rect.y1),
+ ];
+ if area(&points) < 0.0 {
+ points.reverse();
+ }
+ points
+}
+
+fn cross(a: Point, b: Point, p: Point) -> f64 {
+ (b - a).cross(p - a)
+}
+fn area(points: &[Point]) -> f64 {
+ if points.len() < 3 {
+ return 0.0;
+ }
+ points
+ .iter()
+ .zip(points.iter().cycle().skip(1))
+ .take(points.len())
+ .map(|(a, b)| a.x * b.y - a.y * b.x)
+ .sum::<f64>()
+ * 0.5
+}
+fn contains(polygon: &[Point], point: Point) -> bool {
+ polygon
+ .iter()
+ .zip(polygon.iter().cycle().skip(1))
+ .take(polygon.len())
+ .all(|(a, b)| cross(*a, *b, point) >= -1e-6)
+}
+fn clip_rect(polygon: Polygon, rect: Rect) -> Polygon {
+ intersect(polygon, &rectangle(Affine::IDENTITY, rect))
+}
+
+// Sutherland–Hodgman clipping: both the link rectangle and transformed
+// rectangular clips are convex. Preserve their actual polygons, not their AABBs.
+fn intersect(mut polygon: Polygon, clip: &[Point]) -> Polygon {
+ if area(clip).abs() <= 1e-6 {
+ return Vec::new();
+ }
+ for (a, b) in clip
+ .iter()
+ .zip(clip.iter().cycle().skip(1))
+ .take(clip.len())
+ {
+ let Some(mut previous) = polygon.last().copied() else {
+ break;
+ };
+ let mut out = Vec::new();
+ let mut prev_side = cross(*a, *b, previous);
+ for point in polygon {
+ let side = cross(*a, *b, point);
+ if (side >= 0.0) != (prev_side >= 0.0) {
+ let t = prev_side / (prev_side - side);
+ out.push(previous.lerp(point, t));
+ }
+ if side >= 0.0 {
+ out.push(point);
+ }
+ previous = point;
+ prev_side = side;
+ }
+ polygon = out;
+ }
+ polygon
+}
+
+fn edges(path: &BezPath) -> Vec<(Point, Point)> {
+ let mut edges = Vec::new();
+ let mut start = Point::ZERO;
+ let mut previous = Point::ZERO;
+ peniko::kurbo::flatten(path.iter(), 0.1, |element| match element {
+ PathEl::MoveTo(p) => {
+ if previous != start {
+ edges.push((previous, start));
+ }
+ start = p;
+ previous = p;
+ }
+ PathEl::LineTo(p) => {
+ edges.push((previous, p));
+ previous = p;
+ }
+ PathEl::ClosePath => {
+ edges.push((previous, start));
+ previous = start;
+ }
+ _ => unreachable!(),
+ });
+ if previous != start {
+ edges.push((previous, start));
+ }
+ edges
+}
+
+// PDF links only accept quadrilaterals. Approximate curved/non-convex clips
+// with half-CSS-pixel scanline strips using the same nonzero winding rule as
+// paint. This retains holes and avoids clickable bounding-box corners.
+fn curved_clip(
+ polygon: Polygon,
+ edges: &[(Point, Point)],
+ bounds: Rect,
+ out: &mut Vec<Polygon>,
+ budget: &mut usize,
+) -> Result<(), PdfError> {
+ let polygon = clip_rect(polygon, bounds);
+ if area(&polygon).abs() <= 1e-6 {
+ return Ok(());
+ }
+ let y0 = polygon.iter().map(|p| p.y).fold(f64::INFINITY, f64::min);
+ let y1 = polygon
+ .iter()
+ .map(|p| p.y)
+ .fold(f64::NEG_INFINITY, f64::max);
+ let rows = ((y1 - y0) * 2.0).ceil() as usize;
+ spend(budget, rows.saturating_mul(edges.len().max(1)))?;
+ for row in 0..rows {
+ let top = y0 + row as f64 * 0.5;
+ let bottom = (top + 0.5).min(y1);
+ let y = (top + bottom) * 0.5;
+ let mut crossings = edges
+ .iter()
+ .filter_map(|(a, b)| {
+ if (a.y <= y && b.y > y) || (b.y <= y && a.y > y) {
+ Some((
+ a.x + (y - a.y) * (b.x - a.x) / (b.y - a.y),
+ if b.y > a.y { 1 } else { -1 },
+ ))
+ } else {
+ None
+ }
+ })
+ .collect::<Vec<_>>();
+ crossings.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let mut winding = 0;
+ let mut left = 0.0;
+ for (x, delta) in crossings {
+ if winding == 0 {
+ left = x;
+ }
+ winding += delta;
+ if winding == 0 && x > left {
+ spend(budget, polygon.len() + 100)?;
+ let clipped = clip_rect(polygon.clone(), Rect::new(left, top, x, bottom));
+ if area(&clipped).abs() > 1e-6 {
+ out.push(clipped);
+ }
+ }
+ }
+ }
+ Ok(())
+}
diff --git a/moli-paint/src/pdf/links_tests.rs b/moli-paint/src/pdf/links_tests.rs
new file mode 100644
index 000000000..9ab06c678
--- /dev/null
+++ b/moli-paint/src/pdf/links_tests.rs
@@ -0,0 +1,227 @@
+use moli_layout::{
+ PaintColor, PaintFragment, PaintLink, PaintLinkTarget, PaintPoint, PaintRect, PaintShape,
+ PaintSnapshot, PaintTransform2D, PaintViewport,
+};
+
+use super::{PdfOptions, pdf_snapshot};
+
+fn snapshot() -> PaintSnapshot {
+ PaintSnapshot::new(PaintViewport::new(300, 600, 1.0), PaintColor::WHITE)
+}
+fn options() -> PdfOptions {
+ PdfOptions {
+ width: 300.0,
+ height: 300.0,
+ margin_top: 0.0,
+ margin_bottom: 0.0,
+ margin_left: 0.0,
+ margin_right: 0.0,
+ ..Default::default()
+ }
+}
+fn link(snapshot: &mut PaintSnapshot, rect: PaintRect, destination: Option<PaintPoint>) {
+ snapshot.links.push(PaintLink {
+ before_fragment: snapshot.fragments.len(),
+ rect,
+ transform: PaintTransform2D::IDENTITY,
+ target: PaintLinkTarget {
+ url: "https://example.com/doc#target".into(),
+ destination,
+ },
+ });
+}
+fn document(snapshot: &PaintSnapshot, options: &PdfOptions) -> lopdf::Document {
+ lopdf::Document::load_mem(&pdf_snapshot(snapshot, options).unwrap()).unwrap()
+}
+fn annotations(document: &lopdf::Document, page: u32) -> Vec<&lopdf::Dictionary> {
+ let page = document
+ .get_dictionary(document.get_pages()[&page])
+ .unwrap();
+ page.get(b"Annots")
+ .ok()
+ .into_iter()
+ .flat_map(|o| o.as_array().unwrap())
+ .map(|o| {
+ let dict = document.get_dictionary(o.as_reference().unwrap()).unwrap();
+ assert_eq!(dict.get(b"Subtype").unwrap().as_name().unwrap(), b"Link");
+ dict
+ })
+ .collect()
+}
+fn bounds(annotation: &lopdf::Dictionary) -> Vec<f32> {
+ annotation
+ .get(b"Rect")
+ .unwrap()
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|o| o.as_float().unwrap())
+ .collect()
+}
+fn destination_page(document: &lopdf::Document, annotation: &lopdf::Dictionary) -> lopdf::ObjectId {
+ let (_, dest) = document
+ .dereference(annotation.get(b"Dest").unwrap())
+ .unwrap();
+ dest.as_array().unwrap()[0].as_reference().unwrap()
+}
+
+#[test]
+fn links_preserve_separate_lines_and_deduplicate_descendant_regions() {
+ let mut snapshot = snapshot();
+ link(&mut snapshot, PaintRect::new(10.0, 20.0, 100.0, 15.0), None);
+ link(&mut snapshot, PaintRect::new(12.0, 21.0, 96.0, 13.0), None);
+ link(&mut snapshot, PaintRect::new(10.0, 50.0, 60.0, 15.0), None);
+ let doc = document(&snapshot, &options());
+ let annots = annotations(&doc, 1);
+ assert_eq!(annots.len(), 2);
+ for annot in &annots {
+ let action = annot.get(b"A").unwrap().as_dict().unwrap();
+ assert_eq!(action.get(b"S").unwrap().as_name().unwrap(), b"URI");
+ assert_eq!(
+ action.get(b"URI").unwrap().as_str().unwrap(),
+ b"https://example.com/doc#target"
+ );
+ assert_eq!(
+ annot.get(b"QuadPoints").unwrap().as_array().unwrap().len(),
+ 8
+ );
+ let rect = bounds(annot);
+ assert!((rect[3] - rect[1] - 15.0).abs() < 0.01);
+ }
+ assert!(annotations(&doc, 2).is_empty());
+}
+
+#[test]
+fn pagination_clips_links_and_remaps_internal_destinations_to_selected_pages() {
+ let mut snapshot = snapshot();
+ link(
+ &mut snapshot,
+ PaintRect::new(10.0, 280.0, 50.0, 40.0),
+ Some(PaintPoint::new(20.0, 350.0)),
+ );
+ let doc = document(&snapshot, &options());
+ for page in [1, 2] {
+ let annots = annotations(&doc, page);
+ assert_eq!(annots.len(), 1);
+ let rect = bounds(annots[0]);
+ assert!((rect[3] - rect[1] - 20.0).abs() < 0.01);
+ assert_eq!(destination_page(&doc, annots[0]), doc.get_pages()[&2]);
+ }
+ let selected = document(
+ &snapshot,
+ &PdfOptions {
+ page_ranges: std::iter::once(1..=1).collect(),
+ ..options()
+ },
+ );
+ assert_eq!(
+ destination_page(&selected, annotations(&selected, 1)[0]),
+ selected.get_pages()[&1]
+ );
+ let selected = document(
+ &snapshot,
+ &PdfOptions {
+ page_ranges: std::iter::once(0..=0).collect(),
+ ..options()
+ },
+ );
+ let annots = annotations(&selected, 1);
+ assert!(!annots[0].has(b"Dest"));
+ assert!(
+ annots[0].has(b"A"),
+ "an omitted destination uses the original URL"
+ );
+}
+
+#[test]
+fn transformed_clips_and_embedded_snapshots_keep_links_in_their_scopes() {
+ let mut child = snapshot();
+ link(
+ &mut child,
+ PaintRect::new(5.0, 10.0, 100.0, 60.0),
+ Some(PaintPoint::new(8.0, 20.0)),
+ );
+ let mut snapshot = snapshot();
+ snapshot.append_embedded_snapshot(
+ child,
+ PaintRect::new(0.0, 0.0, 50.0, 40.0),
+ PaintTransform2D {
+ coefficients: [1.0, 0.0, 0.5, 1.0, 30.0, 50.0],
+ },
+ );
+ let doc = document(&snapshot, &options());
+ let annots = annotations(&doc, 1);
+ assert_eq!(annots.len(), 1);
+ let rect = bounds(annots[0]);
+ for (actual, expected) in rect.iter().zip([40.0, 210.0, 100.0, 240.0]) {
+ assert!((actual - expected).abs() < 0.01, "{rect:?}");
+ }
+ let quad = annots[0].get(b"QuadPoints").unwrap().as_array().unwrap();
+ assert_ne!(
+ quad[0], quad[6],
+ "skewed hit region must not become its bounding rectangle"
+ );
+ let (_, dest) = doc.dereference(annots[0].get(b"Dest").unwrap()).unwrap();
+ let dest = dest.as_array().unwrap();
+ assert_eq!(dest[2].as_float().unwrap(), 48.0);
+ assert_eq!(dest[3].as_float().unwrap(), 230.0);
+}
+
+#[test]
+fn invisible_and_fully_clipped_links_are_absent_and_invalid_metadata_fails() {
+ let mut snapshot = snapshot();
+ snapshot.push_fragment(PaintFragment::PushClip {
+ shape: PaintShape::Rect(PaintRect::new(0.0, 0.0, 30.0, 30.0)),
+ transform: PaintTransform2D::IDENTITY,
+ });
+ link(&mut snapshot, PaintRect::new(60.0, 0.0, 40.0, 20.0), None);
+ snapshot.push_fragment(PaintFragment::PopLayer);
+ snapshot.push_fragment(PaintFragment::PushLayer {
+ opacity: 0.0,
+ blend_mode: Default::default(),
+ composite: Default::default(),
+ filter: None,
+ clip: PaintShape::Rect(PaintRect::new(0.0, 0.0, 300.0, 300.0)),
+ transform: PaintTransform2D::IDENTITY,
+ });
+ link(&mut snapshot, PaintRect::new(10.0, 10.0, 40.0, 20.0), None);
+ snapshot.push_fragment(PaintFragment::PopLayer);
+ let doc = document(&snapshot, &options());
+ assert!(annotations(&doc, 1).is_empty());
+ snapshot.links[0].before_fragment = usize::MAX;
+ assert!(pdf_snapshot(&snapshot, &options()).is_err());
+ snapshot.links[0].before_fragment = 1;
+ snapshot.links[0].target.destination = Some(PaintPoint::new(f32::NAN, 0.0));
+ assert!(pdf_snapshot(&snapshot, &options()).is_err());
+}
+
+#[test]
+fn curved_clips_do_not_create_clickable_bounding_box_corners() {
+ let mut snapshot = snapshot();
+ let radius = moli_layout::PaintCornerRadius { x: 25.0, y: 25.0 };
+ snapshot.push_fragment(PaintFragment::PushClip {
+ shape: PaintShape::RoundedRect {
+ rect: PaintRect::new(10.0, 10.0, 50.0, 50.0),
+ radii: moli_layout::PaintCornerRadii {
+ top_left: radius,
+ top_right: radius,
+ bottom_left: radius,
+ bottom_right: radius,
+ },
+ },
+ transform: PaintTransform2D::IDENTITY,
+ });
+ link(&mut snapshot, PaintRect::new(10.0, 10.0, 50.0, 50.0), None);
+ snapshot.push_fragment(PaintFragment::PopLayer);
+ let doc = document(&snapshot, &options());
+ let annots = annotations(&doc, 1);
+ assert!(!annots.is_empty());
+ assert!(annots.iter().all(|a| {
+ let r = bounds(a);
+ !(r[0] <= 11.0 && r[2] >= 11.0 && r[1] <= 289.0 && r[3] >= 289.0)
+ }));
+ assert!(annots.iter().any(|a| {
+ let r = bounds(a);
+ r[0] < 35.0 && r[2] > 35.0 && r[1] <= 265.0 && r[3] >= 265.0
+ }));
+}
diff --git a/moli-paint/src/pdf/mod.rs b/moli-paint/src/pdf/mod.rs
index 484417d08..a9cc105d1 100644
--- a/moli-paint/src/pdf/mod.rs
+++ b/moli-paint/src/pdf/mod.rs
@@ -4,6 +4,7 @@
//! effects are rasterized at their own clipped bounds; ordinary text stays text.
mod image;
+mod links;
mod primitives;
mod text;
mod validation;
@@ -125,14 +126,34 @@ pub fn pdf_snapshot(snapshot: &PaintSnapshot, options: &PdfOptions) -> Result<Ve
if selected.is_empty() {
return Err(PdfError::PageRangeExceeded);
}
- if selected.len().saturating_mul(metrics.operation_count) > 20_000_000 {
+ if selected
+ .len()
+ .saturating_mul(metrics.operation_count.saturating_add(snapshot.links.len()))
+ > 20_000_000
+ {
return Err(PdfError::ResourceLimit);
}
let mut document = Document::new();
let mut fonts = text::FontCache::default();
let mut images = std::collections::HashMap::new();
let scopes = primitives::scope_ends(&snapshot.fragments)?;
- for page_index in selected {
+ let regions = links::collect(snapshot)?;
+ if selected.len().saturating_mul(regions.len()) > 1_000_000 {
+ return Err(PdfError::ResourceLimit);
+ }
+ let selected = selected
+ .into_iter()
+ .enumerate()
+ .map(|(output, original)| (original, output))
+ .collect();
+ let page_links = links::PageLinks {
+ regions: &regions,
+ selected: &selected,
+ page_height,
+ scale,
+ options,
+ };
+ for &page_index in selected.keys() {
let top = page_index as f64 * page_height;
let source = Rect::new(0.0, top, printable_width / scale, top + page_height);
let mut page = document.start_page_with(
@@ -169,8 +190,9 @@ pub fn pdf_snapshot(snapshot: &PaintSnapshot, options: &PdfOptions) -> Result<Ve
surface.pop();
surface.pop();
surface.finish();
- page.finish();
result?;
+ page_links.append(&mut page, source)?;
+ page.finish();
}
let mut bytes = document
.finish()
@@ -192,5 +214,7 @@ fn image_size(width: u32, height: u32) -> Result<Size, PdfError> {
Size::from_wh(width as f32, height as f32).ok_or(PdfError::InvalidParameters)
}
+#[cfg(test)]
+mod links_tests;
#[cfg(test)]
mod tests;
diff --git a/moli-paint/src/pdf/validation.rs b/moli-paint/src/pdf/validation.rs
index c3ebb6315..cefbbf4e4 100644
--- a/moli-paint/src/pdf/validation.rs
+++ b/moli-paint/src/pdf/validation.rs
@@ -6,6 +6,26 @@ use super::PdfError;
// raster fallback). Resource identities, operation counts and scope depths are
// checked by the shared paint validator.
pub(super) fn validate(snapshot: &PaintSnapshot) -> Result<(), PdfError> {
+ if snapshot.links.len() > 100_000 {
+ return Err(PdfError::ResourceLimit);
+ }
+ for link in &snapshot.links {
+ if link.before_fragment > snapshot.fragments.len()
+ || !rect(link.rect)
+ || link.rect.width < 0.0
+ || link.rect.height < 0.0
+ || !link
+ .transform
+ .coefficients
+ .into_iter()
+ .all(|v| (v as f32).is_finite())
+ || link.target.destination.is_some_and(|p| !point(p))
+ || link.target.url.is_empty()
+ || link.target.url.len() > 65_536
+ {
+ return Err(PdfError::Encoding("invalid hyperlink metadata".into()));
+ }
+ }
for fragment in &snapshot.fragments {
let (valid, matrix) = match fragment {
PaintFragment::PushLayer {
diff --git a/moli-renderer-v8/src/layout_renderer/source_view.rs b/moli-renderer-v8/src/layout_renderer/source_view.rs
index ab9e7148a..d7597e68f 100644
--- a/moli-renderer-v8/src/layout_renderer/source_view.rs
+++ b/moli-renderer-v8/src/layout_renderer/source_view.rs
@@ -99,6 +99,42 @@ impl LayoutSource for NativeLayoutSourceView<'_> {
native_flat_parent(self.host(), self.root, node)
}
+ fn hyperlink(&self, node: DomHandle) -> Option<moli_layout::LayoutHyperlink<DomHandle>> {
+ let host = self.host();
+ if !host.is_html_element_named(node, "a") {
+ return None;
+ }
+ let document = self.document?;
+ let href = host.get_attribute(node, "href")?;
+ let url = host
+ .document_base_url_for_handle(document)?
+ .join(&href)
+ .ok()?;
+ // JavaScript handlers have no equivalent in a static PDF.
+ if url.scheme() == "javascript" {
+ return None;
+ }
+ let mut without_fragment = url.clone();
+ without_fragment.set_fragment(None);
+ let mut document_url = host.document_url_for_handle(document)?.clone();
+ document_url.set_fragment(None);
+ let destination = if without_fragment == document_url {
+ let fragment = url.fragment().unwrap_or_default();
+ let decoded = percent_encoding::percent_decode_str(fragment).decode_utf8_lossy();
+ host.find_document_anchor(document, fragment)
+ .or_else(|| host.find_document_anchor(document, &decoded))
+ .or_else(|| {
+ (decoded.is_empty() || decoded.eq_ignore_ascii_case("top")).then_some(self.root)
+ })
+ } else {
+ None
+ };
+ Some(moli_layout::LayoutHyperlink {
+ url: url.as_str().into(),
+ destination,
+ })
+ }
+
fn flat_children(&self, node: Self::NodeId) -> Self::ChildIter<'_> {
native_flat_children(self.host(), self.root, node).into_iter()
}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs
index ad696a1f8..04ff15053 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/print.rs
@@ -4,6 +4,92 @@ use crate::runtime::{
RendererPrintToPdfRequest, RendererScreenshotPurpose,
};
+#[tokio::test(flavor = "current_thread")]
+async fn native_pdf_resolves_links_base_urls_anchors_and_embedded_frames() {
+ run_page_vm_async_test(async move {
+ let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?;
+ let mut page_vm = test_page_vm_with_loader_and_document_url(
+ &loader,
+ Vec::new(),
+ Url::parse("https://example.com/doc.html")?,
+ );
+ page_vm.set_viewport_surface(Some(crate::protocol_types::ViewportSurface {
+ inner_width: 300,
+ inner_height: 300,
+ ..Default::default()
+ }))?;
+ page_vm.vm_mut().eval(
+ r#"
+document.head.innerHTML = `<base href="https://example.org/base/"><style>
+body { margin:0 } a { display:block; width:100px; height:20px }
+iframe { position:absolute; left:120px; top:20px; width:120px; height:80px; border:0 }
+#destination { position:absolute; top:400px; height:20px }
+</style>`;
+document.body.innerHTML = `<a href="../relative?q=1&amp;x=2">Relative</a>
+<a href="mailto:[email protected]">Mail</a>
+<a href="https://example.com/doc.html#dest%20name">Internal</a>
+<a href="javascript:void(0)">Script</a>
+<a href="https://hidden.invalid/" style="opacity:0">Hidden</a>
+<a href="https://display.invalid/" style="display:none">None</a>
+<div id="destination"><span id="dest name">Destination</span></div>
+<iframe id=frame></iframe>`;
+frame.contentDocument.body.innerHTML = '<a href="https://child.example/link">Child</a>';
+'installed'
+"#,
+ )?;
+ let request = RendererPrintToPdfRequest {
+ options: moli_paint::pdf::PdfOptions {
+ width: 300.0,
+ height: 300.0,
+ margin_left: 0.0,
+ margin_right: 0.0,
+ margin_top: 0.0,
+ margin_bottom: 0.0,
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let RendererPrintToPdfReply::Printed(bytes) = page_vm.print_to_pdf(request)? else {
+ anyhow::bail!("print failed");
+ };
+ let doc = lopdf::Document::load_mem(&bytes)?;
+ let mut urls = std::collections::BTreeSet::new();
+ let mut destinations = Vec::new();
+ for object in doc.objects.values() {
+ let Ok(dict) = object.as_dict() else { continue };
+ if dict.get(b"Subtype").and_then(|o| o.as_name()).ok() != Some(b"Link") {
+ continue;
+ }
+ if let Ok(action) = dict.get(b"A") {
+ let action = action.as_dict()?;
+ urls.insert(String::from_utf8(action.get(b"URI")?.as_str()?.to_vec())?);
+ } else {
+ let (_, dest) = doc.dereference(dict.get(b"Dest")?)?;
+ destinations.push(dest.as_array()?[0].as_reference()?);
+ }
+ }
+ assert_eq!(
+ urls,
+ [
+ "https://example.org/relative?q=1&x=2",
+ "mailto:[email protected]",
+ "https://child.example/link"
+ ]
+ .map(str::to_owned)
+ .into()
+ );
+ assert!(!destinations.is_empty());
+ assert!(destinations.iter().all(|id| *id == doc.get_pages()[&2]));
+ assert_eq!(
+ page_vm.vm_mut().eval("matchMedia('print').matches")?,
+ "false"
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("print links preserve URL and document ownership");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn native_pdf_restores_media_on_success_and_failure_and_keeps_iframe_text() {
run_page_vm_async_test(async move {