Size PDF figure placeholders from their page aspect

This commit is contained in:
gloamxun committed 2026-10-20 02:00:40 +08:00
1 parent 77f672f156
commit 93bc5ac945
2 files changed
+33 -2

No files matched your search

+3
View File
@@ -545,3 +545,6 @@ The SIVP class (`sn-jnl.cls`) loads completely and `sn-article.tex` previews and
The compatibility layer also covers spacing macros, text symbols/letters, style
commands, break advisories, and document metadata; see the sections above.
PDF-only figures are rendered as placeholders sized from the source PDF page aspect ratio (until native PDF page embedding lands).
+30 -2
View File
@@ -766,6 +766,26 @@ fn layout_table(
}
#[allow(clippy::too_many_arguments)]
fn pdf_page_aspect(path: &Path) -> Option<f64> {
let data = std::fs::read(path).ok()?;
let key = b"/MediaBox";
let key_pos = data.windows(key.len()).position(|window| window == key)?;
let rest = &data[key_pos + key.len()..];
let open = rest.iter().position(|byte| *byte == b'[')?;
let close = rest[open..].iter().position(|byte| *byte == b']')?;
let text = std::str::from_utf8(&rest[open + 1..open + close]).ok()?;
let numbers: Vec<f64> = text
.split_whitespace()
.filter_map(|value| value.parse().ok())
.collect();
if numbers.len() < 4 {
return None;
}
let width = (numbers[2] - numbers[0]).abs();
let height = (numbers[3] - numbers[1]).abs();
(height > 0.0).then_some(width / height)
}
fn layout_figure(
source_dir: &Path,
path: &str,
@@ -786,6 +806,7 @@ fn layout_figure(
let is_pdf = requested_path
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("pdf"));
let pdf_aspect = is_pdf.then(|| pdf_page_aspect(&requested_path)).flatten();
let (image_path, pixel_width, pixel_height) = match image::image_dimensions(&requested_path) {
Ok((width, height)) => (requested_path, width, height),
Err(_) if is_pdf => {
@@ -797,15 +818,22 @@ fn layout_figure(
}
Err(_) => return None,
};
let (scale_x, scale_y) = image_scale(
let (scale_x, mut scale_y) = image_scale(
options,
pixel_width,
pixel_height,
content_width_mm,
content_height_mm,
);
let image_height_mm = f64::from(pixel_height) * 25.4 / 300.0 * scale_y;
let mut image_height_mm = f64::from(pixel_height) * 25.4 / 300.0 * scale_y;
let image_width_mm = f64::from(pixel_width) * 25.4 / 300.0 * scale_x;
if let Some(aspect) = pdf_aspect {
let height_mm = image_width_mm / aspect;
if height_mm > 0.0 && height_mm <= content_height_mm {
image_height_mm = height_mm;
scale_y = height_mm / (f64::from(pixel_height) * 25.4 / 300.0);
}
}
if !image_height_mm.is_finite() || image_height_mm <= 0.0 {
return None;
}