M2: pages with /UserUnit are shown at their size in points, as in Acrobat (#722)

* M2: pages with /UserUnit are shown at their size in points, as in Acrobat

/UserUnit gives the size of a page's user-space unit in points; PdfCraft
ignored it everywhere except the measuring tools, so a /UserUnit 2 page
was shown, extracted, printed and edited at half its size, and the
measuring tools disagreed with the rest of the app.

The value is now read as Acrobat reads it (the page's own entry, a number
from 1 up, at most 75,000; anything else counts as 1) in two places:
- vendored hayro-syntax Page (patch 13): render_dimensions and
  initial_transform give the page in points, so rendering, tiles,
  PageInfo and the text layer follow; a page without it keeps exactly
  the transform it had.
- pdfcraft-model Page: user_unit(), and display_size/view_matrix in
  points, so print, header/footer, watermark, background, added content
  and measuring agree with the screen. The measure crate drops its own
  arithmetic. Added items record the /UserUnit they were written for;
  items without the record (written before) read back converted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* M2: an added item's recorded /UserUnit is clamped like the page's

An infinite or huge recorded /UserUnit made the scale factor 0 and collapsed the item.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Brandon Thomas <echelon@gmail.com>
This commit is contained in:
cyfung1031
2026-10-10 06:19:31 -04:00
committed by GitHub
co-authored by Claude Opus 5.5 Brandon Thomas
parent 99c7dd9311
commit d94da2038a
10 changed files with 243 additions and 34 deletions
+29 -5
View File
@@ -4,8 +4,9 @@
//! parameters (text, font, size, colour, alignment, box; or image and box) kept in the stream
//! dictionary under `/PCAdded`. That keeps the item editable later (move, resize, retype,
//! reformat, delete) without content-stream surgery, while every viewer sees ordinary page
//! content. Boxes are in display space (origin at the bottom-left of the page as shown, after
//! `/Rotate`), so items stay upright on rotated pages.
//! content. Boxes are in display space (points, origin at the bottom-left of the page as shown,
//! after `/UserUnit` and `/Rotate`), so items stay upright on rotated pages; an item records the
//! `/UserUnit` it was written for.
use std::collections::HashMap;
@@ -170,6 +171,15 @@ impl Content {
}
}
/// The same item with its box and text size scaled by `factor`.
fn scaled(self, factor: f64) -> Content {
match self {
_ if factor == 1.0 => self,
Content::Text(t) => Content::Text(AddedText { rect: t.rect.map(|v| v * factor), size: t.size * factor, ..t }),
Content::Image(i) => Content::Image(AddedImage { rect: i.rect.map(|v| v * factor), ..i }),
}
}
/// The same item moved/resized to `rect` (text keeps its computed height).
pub fn with_rect(&self, rect: [f64; 4]) -> Content {
match self {
@@ -762,6 +772,7 @@ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option<ObjRef>) -> R
check(&[page], all.len())?;
let p = &all[page];
let view = p.view_matrix(doc);
let user_unit = p.user_unit(doc);
// The page gets its own copy of its resources with the item's fonts and images added, and
// without the Arabic fonts of the version it replaces.
let mut pres = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
@@ -780,7 +791,11 @@ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option<ObjRef>) -> R
doc.update_dict(p.obj, |d| d.set(b"Resources".to_vec(), Object::Dict(pres)))?;
let mut sd = Dict::new();
sd.set(b"PCMark".to_vec(), Object::name(TAG));
sd.set(b"PCAdded".to_vec(), Object::Dict(params(c)));
let mut added = params(c);
if user_unit != 1.0 {
added.set(b"UserUnit".to_vec(), Object::Real(user_unit));
}
sd.set(b"PCAdded".to_vec(), Object::Dict(added));
let stream = Stream::flate(sd, &content);
match obj {
Some(r) => {
@@ -817,8 +832,17 @@ pub fn list_added(doc: &Document) -> Vec<Added> {
if d.name(b"PCMark") != Some(TAG.as_bytes()) {
continue;
}
if let Some(c) = d.get(b"PCAdded").and_then(|p| doc.resolve(p).as_dict().cloned()).and_then(|p| parse(doc, &p)) {
out.push(Added { page: pi, obj: r, content: c });
let Some(params) = d.get(b"PCAdded").and_then(|o| doc.resolve(o).as_dict().cloned()) else { continue };
if let Some(c) = parse(doc, &params) {
// Display points depend on the page's /UserUnit. An item records the one it was
// written for; none means 1, as for items written before display space followed
// /UserUnit.
let written = params
.get(b"UserUnit")
.and_then(Object::as_f64)
.filter(|u| u.is_finite() && *u >= 1.0)
.map_or(1.0, |u| u.min(pdfcraft_model::MAX_USER_UNIT));
out.push(Added { page: pi, obj: r, content: c.scaled(p.user_unit(doc) / written) });
}
}
}
+33
View File
@@ -175,6 +175,39 @@ fn flattening_draws_appearances_into_the_page_and_removes_the_comments() {
assert!(marks_present(&doc).is_empty(), "flattened content is not a removable mark");
}
/// Display space is in points, so on a `/UserUnit 2` page an item's box maps to half as many
/// user-space units. Items record the `/UserUnit` they were written for; one without it was
/// written when display space was in user-space units, and reads back scaled to points.
#[test]
fn added_items_follow_the_page_user_unit() {
let mut doc = fixture();
let page = pdfcraft_model::pages(&doc)[2].obj;
doc.update_dict(page, |d| d.set(b"UserUnit".to_vec(), Object::Int(2))).unwrap();
let text = AddedText { rect: [72.0, 600.0, 300.0, 700.0], text: "Scaled".into(), size: 14.0, ..AddedText::default() };
add_content(&mut doc, 2, &Content::Text(text.clone())).unwrap();
add_content(&mut doc, 0, &Content::Text(text.clone())).unwrap();
let doc = reopen(&doc);
let all = list_added(&doc);
let on = |page: usize| all.iter().find(|a| a.page == page).unwrap();
let Content::Text(t) = &on(2).content else { panic!() };
assert_eq!((t.rect[0], t.rect[2], t.rect[3], t.size), (72.0, 300.0, 700.0, 14.0), "read back as written");
assert!(streams(&doc, 2).iter().any(|s| s.starts_with("q 0.5 0 0 0.5 0 0 cm")), "display points to user space");
let recorded = |doc: &Document, a: &Added| {
doc.get(a.obj).as_dict().and_then(|d| d.get(b"PCAdded").cloned()).and_then(|p| p.as_dict().and_then(|p| p.get(b"UserUnit").cloned()))
};
assert!(recorded(&doc, on(0)).is_none(), "a page without /UserUnit records nothing");
assert_eq!(recorded(&doc, on(2)).and_then(|u| u.as_f64()), Some(2.0));
// The same item as an earlier version wrote it: no record, box and size in user-space units.
let mut legacy = doc.clone();
let Object::Stream(mut s) = (*legacy.get(on(2).obj)).clone() else { panic!() };
let mut params = s.dict.get(b"PCAdded").and_then(|p| p.as_dict().cloned()).unwrap();
params.remove(b"UserUnit");
s.dict.set(b"PCAdded".to_vec(), Object::Dict(params));
legacy.set(on(2).obj, Object::Stream(s));
let Content::Text(old) = &list_added(&legacy).into_iter().find(|a| a.page == 2).unwrap().content else { panic!() };
assert_eq!((old.rect[0], old.rect[2], old.rect[3], old.size), (144.0, 600.0, 1400.0, 28.0), "scaled to points");
}
#[test]
fn added_text_and_images_are_page_content_that_stays_editable() {
let mut doc = fixture();
+3 -12
View File
@@ -470,8 +470,7 @@ pub fn scale_at(doc: &Document, page_index: usize, at: Point) -> Result<Scale> {
}
}
}
let user_unit = p.dict.get(b"UserUnit").and_then(Object::as_f64).unwrap_or(1.0);
Scale::new(user_unit / 72.0, "in", 2)
Scale::new(p.user_unit(doc) / 72.0, "in", 2)
}
/// Add a named rectangular viewport. Existing viewports are preserved in drawing order.
pub fn set_scale(doc: &mut Document, page_index: usize, bbox: [f64; 4], name: &str, scale: &Scale) -> Result<()> {
@@ -531,25 +530,17 @@ mod tests;
pub fn view_to_user(doc: &Document, page_index: usize, at: Point) -> Result<Point> {
check_points(&[at])?;
let page = page(doc, page_index)?;
let unit = page.dict.get(b"UserUnit").and_then(Object::as_f64).unwrap_or(1.0);
if !unit.is_finite() || unit <= 0.0 || unit > 75000.0 {
return Err(invalid("invalid page UserUnit"));
}
let (_, height) = page.display_size(doc);
let m = pdfcraft_content::Matrix(page.view_matrix(doc));
let (x, y) = m.apply(at[0] / unit, height - at[1] / unit);
let (x, y) = m.apply(at[0], height - at[1]);
check_points(&[[x, y]])?;
Ok([x, y])
}
pub fn user_to_view(doc: &Document, page_index: usize, at: Point) -> Result<Point> {
check_points(&[at])?;
let page = page(doc, page_index)?;
let unit = page.dict.get(b"UserUnit").and_then(Object::as_f64).unwrap_or(1.0);
if !unit.is_finite() || unit <= 0.0 || unit > 75000.0 {
return Err(invalid("invalid page UserUnit"));
}
let (_, height) = page.display_size(doc);
let m = pdfcraft_content::Matrix(page.view_matrix(doc)).invert().ok_or_else(|| invalid("invalid page transform"))?;
let (x, y) = m.apply(at[0], at[1]);
Ok([x * unit, (height - y) * unit])
Ok([x, height - y])
}
+13
View File
@@ -319,3 +319,16 @@ fn indirect_viewport_array_stays_indirect() {
assert_eq!(d.get(r).as_array().map(Vec::len), Some(1));
close(scale_at(&d, 0, [50.0, 50.0]).unwrap().x, 1.0);
}
#[test]
fn user_unit_is_read_as_acrobat_reads_it() {
// Values below 1 and values that aren't numbers count as 1, values over 75,000 as 75,000.
for (attrs, unit) in [("/UserUnit 0", 1.0), ("/UserUnit 0.5", 1.0), ("/UserUnit (2)", 1.0), ("/UserUnit 100000", 75_000.0)] {
let d = fixture("", attrs, &[]);
close(scale_at(&d, 0, [50.0, 50.0]).unwrap().x, unit / 72.0);
let user = view_to_user(&d, 0, [36.0, 72.0]).unwrap();
let view = user_to_view(&d, 0, user).unwrap();
close(view[0], 36.0);
close(view[1], 72.0);
}
}
+5 -3
View File
@@ -5,9 +5,11 @@ L3/L4 crates need:
- `pages(doc)`: leaf pages in order, each with its inherited attributes (`Resources`,
`MediaBox`, `CropBox`, `Rotate`, §7.7.3.4) resolved;
- `Page::crop`, `Page::rotation` and `Page::view_matrix`: the displayed page's geometry, and the
matrix from "display space" (origin at the bottom-left of the page as shown, after `/Rotate`)
to user space, so content can be placed the way the reader sees the page.
- `Page::crop`, `Page::rotation`, `Page::user_unit` and `Page::view_matrix`: the displayed page's
geometry, and the matrix from "display space" (points, origin at the bottom-left of the page as
shown, after `/UserUnit` and `/Rotate`) to user space, so content can be placed the way the
reader sees the page. `/UserUnit` is read as Acrobat reads it: the page's own entry, a number
from 1 up, at most 75,000; anything else counts as 1.
`view_matrix_for(rotation, rect)` is the same matrix for any rectangle, e.g. to draw a
comment's picture upright inside its user-space `/Rect` on a turned page.
+53 -7
View File
@@ -7,6 +7,9 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object};
/// Attributes a page inherits from its ancestors (ISO 32000-2 §7.7.3.4).
pub const INHERITABLE: [&[u8]; 4] = [b"Resources", b"MediaBox", b"CropBox", b"Rotate"];
/// The largest `/UserUnit` honoured, as in Acrobat (a larger value counts as this one).
pub const MAX_USER_UNIT: f64 = 75_000.0;
/// A leaf page and its effective (inherited) attributes.
#[derive(Clone, Debug, PartialEq)]
pub struct Page {
@@ -39,17 +42,26 @@ impl Page {
self.dict.get(b"Rotate").and_then(|o| doc.resolve(o).as_int()).unwrap_or(0).rem_euclid(360) / 90 * 90
}
/// The displayed size (width, height) in points.
/// The size of the page's user-space unit in points (`/UserUnit`; it isn't inherited), read
/// as Acrobat reads it: a number from 1 up, at most [`MAX_USER_UNIT`]; anything else is 1.
pub fn user_unit(&self, doc: &Document) -> f64 {
self.dict.get(b"UserUnit").and_then(|o| doc.resolve(o).as_f64()).filter(|u| *u >= 1.0).map_or(1.0, |u| u.min(MAX_USER_UNIT))
}
/// The displayed size (width, height) in points, after `/UserUnit` and `/Rotate`.
pub fn display_size(&self, doc: &Document) -> (f64, f64) {
let c = self.crop(doc);
let (w, h) = (c[2] - c[0], c[3] - c[1]);
let u = self.user_unit(doc);
let (w, h) = ((c[2] - c[0]) * u, (c[3] - c[1]) * u);
if self.rotation(doc) % 180 == 0 { (w, h) } else { (h, w) }
}
/// The matrix `[a b c d e f]` from display space (origin at the bottom-left of the page as
/// shown, y up, after `/Rotate`) to user space.
/// The matrix `[a b c d e f]` from display space (points, origin at the bottom-left of the
/// page as shown, y up, after `/UserUnit` and `/Rotate`) to user space.
pub fn view_matrix(&self, doc: &Document) -> [f64; 6] {
view_matrix_for(self.rotation(doc), self.crop(doc))
let m = view_matrix_for(self.rotation(doc), self.crop(doc));
let u = self.user_unit(doc);
if u == 1.0 { m } else { [m[0] / u, m[1] / u, m[2] / u, m[3] / u, m[4], m[5]] }
}
}
@@ -117,10 +129,15 @@ mod tests {
use super::*;
fn doc(rotate: i64) -> Document {
doc_with(rotate, "", "")
}
/// `pages` and `page` add entries to the page tree node and to the page.
fn doc_with(rotate: i64, pages: &str, page: &str) -> Document {
let objs = [
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
format!("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] /Rotate {rotate} /Resources << /Font << >> >> >>"),
"<< /Type /Page /Parent 2 0 R /CropBox [10 20 210 320] >>".to_string(),
format!("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] /Rotate {rotate} /Resources << /Font << >> >> {pages} >>"),
format!("<< /Type /Page /Parent 2 0 R /CropBox [10 20 210 320] {page} >>"),
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offs = Vec::new();
@@ -166,4 +183,33 @@ mod tests {
assert_eq!(tl, expect, "rotation {rotate}");
}
}
/// Display space is in points: `/UserUnit 2` doubles it. As in Acrobat, the value isn't
/// inherited, values below 1 or not numbers count as 1, and values over 75,000 as 75,000.
#[test]
fn user_unit_scales_display_space() {
for rotate in [0, 90, 180, 270] {
let d = doc_with(rotate, "", "/UserUnit 2");
let p = &pages(&d)[0];
let (w, h) = p.display_size(&d);
assert_eq!((w, h), if rotate % 180 == 0 { (400.0, 600.0) } else { (600.0, 400.0) }, "{rotate}");
let plain = doc(rotate);
let unscaled = pages(&plain)[0].view_matrix(&plain);
for (x, y) in [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h), (37.0, 81.0)] {
assert_eq!(apply(p.view_matrix(&d), x, y), apply(unscaled, x / 2.0, y / 2.0), "{rotate}: ({x}, {y})");
}
}
for (pages_attrs, page_attrs, unit) in [
("/UserUnit 2", "", 1.0),
("", "/UserUnit 1.5", 1.5),
("", "/UserUnit 0.5", 1.0),
("", "/UserUnit 0", 1.0),
("", "/UserUnit -2", 1.0),
("", "/UserUnit /Two", 1.0),
("", "/UserUnit 100000", MAX_USER_UNIT),
] {
let d = doc_with(0, pages_attrs, page_attrs);
assert_eq!(pages(&d)[0].user_unit(&d), unit, "{pages_attrs} {page_attrs}");
}
}
}
+70
View File
@@ -3840,6 +3840,76 @@ trailer << /Root 1 0 R >>
assert!(px.rgba[((50 * px.width + 25) * 4) as usize] < 64, "the glyph is drawn");
}
/// A page's `/UserUnit` (the size of its unit in points) scales the page and everything on
/// it, after the crop box and before `/Rotate`, as Acrobat shows such pages: with
/// `/UserUnit 2`, scale 1 renders pixel for pixel what scale 2 renders without it. As in
/// Acrobat, values below 1, values that aren't numbers and a value on a parent `/Pages`
/// node count as 1, and values over 75,000 count as 75,000.
#[test]
fn user_unit_scales_the_page_and_everything_on_it() {
let content = "1 0 0 rg 20 10 30 20 re f BT /F1 18 Tf 15 50 Td (Hg) Tj ET q 16 0 0 8 60 30 cm BI /W 2 /H 2 /CS /RGB /BPC 8 /F /AHx ID 0000FFFF000000FF00FFFF00> EI Q";
let pdf = |page: &str, parent: &str| {
format!(
"%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 {parent} >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 80] /CropBox [10 6 90 76] {page} /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj
4 0 obj << /Length {} >> stream
{content}
endstream endobj
5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj
6 0 obj 2 endobj
trailer << /Root 1 0 R >>
%%EOF",
content.len()
)
.into_bytes()
};
let render = |bytes: Vec<u8>, scale: f32| {
let mut r = PageRenderer::new(Arc::new(bytes), RenderConfig::default());
let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale, tag: 0 });
assert!(p.error.is_none(), "{:?}", p.error);
p
};
let glyphs = |bytes: Vec<u8>| {
let parsed = Pdf::new(Arc::new(bytes)).expect("parses");
crate::text::extract_page(&parsed, 0, &InterpreterSettings::default()).expect("text").glyphs
};
let size = |bytes: Vec<u8>| {
let p = &crate::inspect(Arc::new(bytes), None).expect("opens").pages[0];
(p.width, p.height)
};
for rotate in [0, 90, 180, 270] {
let turned = format!("/Rotate {rotate}");
let (w, h) = if rotate % 180 == 0 { (80.0, 70.0) } else { (70.0, 80.0) };
let plain = render(pdf(&turned, ""), 2.0);
let one = render(pdf(&turned, ""), 1.0);
let plain_glyphs = glyphs(pdf(&turned, ""));
for unit in ["/UserUnit 2", "/UserUnit 6 0 R"] {
let page = format!("{turned} {unit}");
assert_eq!(size(pdf(&page, "")), (w * 2.0, h * 2.0), "{page}");
let doubled = render(pdf(&page, ""), 1.0);
assert_eq!((doubled.width, doubled.height), (plain.width, plain.height), "{page}");
assert!(doubled.rgba == plain.rgba, "{page}: the page renders as at twice the scale");
let doubled_glyphs = glyphs(pdf(&page, ""));
assert_eq!(doubled_glyphs.len(), plain_glyphs.len(), "{page}");
for (d, p) in doubled_glyphs.iter().zip(&plain_glyphs) {
assert_eq!(d.rect, p.rect.map(|v| v * 2.0), "{page}: text layer");
}
}
for unit in ["/UserUnit 1", "/UserUnit 0", "/UserUnit -1", "/UserUnit 0.5", "/UserUnit /Two", "/UserUnit (2)"] {
let page = format!("{turned} {unit}");
assert_eq!(size(pdf(&page, "")), (w, h), "{page}");
assert!(render(pdf(&page, ""), 1.0).rgba == one.rgba, "{page} counts as 1");
}
assert_eq!(size(pdf(&turned, "/UserUnit 2")), (w, h), "not inherited from /Pages");
assert!(render(pdf(&turned, "/UserUnit 2"), 1.0).rgba == one.rgba, "not inherited from /Pages");
for unit in ["/UserUnit 75000", "/UserUnit 100000"] {
assert_eq!(size(pdf(&format!("{turned} {unit}"), "")), (w * 75_000.0, h * 75_000.0), "{unit}");
}
}
}
#[test]
fn tiles_match_full_render() {
let mut r = PageRenderer::new(Arc::new(ONE_PAGE.to_vec()), RenderConfig::default());
+2 -2
View File
@@ -698,8 +698,8 @@ milestone = "M2"
status = "partial"
commands = []
tools = ["page_render"]
evidence = ["crates/render/src/raster.rs::renders_a_blue_rectangle", "crates/automation/tests/automation.rs::open_inspect_render_and_find"]
notes = "hayro bootstrap renderer; own DisplayList devices in M2.6"
evidence = ["crates/render/src/raster.rs::renders_a_blue_rectangle", "crates/automation/tests/automation.rs::open_inspect_render_and_find", "crates/render/src/raster.rs::user_unit_scales_the_page_and_everything_on_it"]
notes = "hayro bootstrap renderer; own DisplayList devices in M2.6. Pages with /UserUnit are shown at their size in points, as Acrobat reads the value"
[[feature]]
id = "view.render-shadings-patterns"
+1 -1
View File
File diff suppressed because one or more lines are too long
+34 -4
View File
@@ -112,6 +112,10 @@ impl<'a> Deref for Pages<'a> {
/// PdfCraft patch: maximum page-tree depth (direct dictionaries have no id to track).
const MAX_PAGE_TREE_DEPTH: usize = 256;
/// PdfCraft patch: the largest `/UserUnit` honoured, as in Acrobat (a larger value counts as
/// this one).
const MAX_USER_UNIT: f64 = 75_000.0;
fn resolve_pages<'a>(
pages_dict: &Dict<'a>,
entries: &mut Vec<Page<'a>>,
@@ -185,6 +189,7 @@ pub struct Page<'a> {
media_box: Rect,
crop_box: Rect,
rotation: Rotation,
user_unit: f32,
page_streams: OnceLock<Option<Vec<u8>>>,
resources: Resources<'a>,
ctx: ReaderContext<'a>,
@@ -223,6 +228,13 @@ impl<'a> Page<'a> {
_ => Rotation::None,
};
// PdfCraft patch: the page's own `/UserUnit` (it isn't inherited), read as Acrobat reads
// it: a number from 1 up, at most `MAX_USER_UNIT`; anything else counts as 1.
let user_unit = dict
.get::<f64>(USER_UNIT)
.filter(|u| *u >= 1.0)
.map_or(1.0, |u| u.min(MAX_USER_UNIT) as f32);
let ctx = resources.ctx.clone();
let resources = Resources::from_parent(
dict.get::<Dict<'_>>(RESOURCES).unwrap_or_default(),
@@ -234,6 +246,7 @@ impl<'a> Page<'a> {
media_box,
crop_box,
rotation,
user_unit,
page_streams: OnceLock::new(),
resources,
ctx,
@@ -313,6 +326,11 @@ impl<'a> Page<'a> {
self.crop_box
}
/// PdfCraft patch: the size of the page's user-space unit in points (`/UserUnit`).
pub fn user_unit(&self) -> f32 {
self.user_unit
}
/// Return the intersection of crop box and media box.
pub fn intersected_crop_box(&self) -> Rect {
self.crop_box().intersect(self.media_box())
@@ -339,7 +357,10 @@ impl<'a> Page<'a> {
/// Depending on the document, it is either based on the media box or the crop box
/// of the page. In addition to that, it also takes the rotation of the page into account.
pub fn render_dimensions(&self) -> (f32, f32) {
let (mut base_width, mut base_height) = self.base_dimensions();
let (base_width, base_height) = self.base_dimensions();
// PdfCraft patch: in points, after `/UserUnit`.
let (mut base_width, mut base_height) =
(base_width * self.user_unit, base_height * self.user_unit);
if matches!(
self.rotation(),
@@ -379,6 +400,8 @@ impl<'a> Page<'a> {
pub fn initial_transform(&self, invert_y: bool) -> Transform {
let crop_box = self.intersected_crop_box();
let (_, base_height) = self.base_dimensions();
// PdfCraft patch: the page in points, after `/UserUnit`.
let base_height = base_height * self.user_unit;
let (width, height) = self.render_dimensions();
let horizontal_t = Transform::ROTATE_CW_90 * Transform::translate((0.0, -width as f64));
@@ -412,9 +435,16 @@ impl<'a> Page<'a> {
Transform::IDENTITY
};
rotation_transform
* inversion_transform
* Transform::translate((-crop_box.x0, -crop_box.y0))
let user_space = Transform::translate((-crop_box.x0, -crop_box.y0));
// PdfCraft patch: user space in units of `/UserUnit` points. A page without it keeps
// exactly the transform it had.
let user_space = if self.user_unit == 1.0 {
user_space
} else {
Transform::scale(f64::from(self.user_unit)) * user_space
};
rotation_transform * inversion_transform * user_space
}
}