Promote verified native PDF and box capacity support

This commit is contained in:
gloamxun committed 2026-11-19 14:39:39 +08:00
1 parent 3706afa483
commit 72ed779749
31 files changed
+1042 -78

No files matched your search

+102 -8
View File
@@ -1,4 +1,5 @@
//! Embedded PDF pages and the resource objects reachable from their content.
//! Native image XObjects and the resource objects reachable from their content.
mod jpeg;
use crate::resources::{LoadedResource, ResourceVersion};
use lopdf::{Dictionary, Document, Object, ObjectId};
use std::{
@@ -33,7 +34,7 @@ pub struct PdfImage {
pub version: ResourceVersion,
pub page: usize,
pub page_count: usize,
pub natural: [i32; 2],
pub natural: [i64; 2],
extent: [u64; 2],
objects: Vec<Vec<Part>>,
}
@@ -59,7 +60,9 @@ impl PdfImageUse {
image: PdfImage,
requested: [Option<i32>; 3],
) -> Result<Self, String> {
let [w, h] = image.natural.map(i64::from);
let [w, h] = image.natural;
let jpeg = image.jpeg_frame().map(|(size, _)| size.map(i64::from));
let [aspect_width, aspect_height] = jpeg.unwrap_or([w, h]);
let [width, height, depth] = requested.map(|value| value.map(i64::from));
let ratio = |value: i64, numerator: i64, denominator: i64| {
let product = value * numerator;
@@ -67,9 +70,12 @@ impl PdfImageUse {
};
let depth = depth.unwrap_or(0);
let (width, height) = match (width, height) {
(None, None) if jpeg.is_some() && requested[2].is_some() => {
(ratio(h, aspect_width, aspect_height), h - depth)
}
(None, None) => (w, h - depth),
(Some(width), None) => (width, ratio(width, h, w) - depth),
(None, Some(height)) => (ratio(height + depth, w, h), height),
(Some(width), None) => (width, ratio(width, aspect_height, aspect_width) - depth),
(None, Some(height)) => (ratio(height + depth, aspect_width, aspect_height), height),
(Some(width), Some(height)) => (width, height),
};
if [width, height, depth].iter().any(|v| v.abs() > 1073741823) {
@@ -93,6 +99,11 @@ impl PdfImageUse {
enum Part {
Bytes(Vec<u8>),
Ref(usize),
Jpeg {
size: [u16; 2],
precision: u8,
bytes: Vec<u8>,
},
}
pub(crate) fn real(value: f64) -> String {
@@ -101,6 +112,89 @@ pub(crate) fn real(value: f64) -> String {
}
impl PdfImage {
pub(crate) fn is_jpeg(resource: &LoadedResource) -> bool {
resource.data.starts_with(jpeg::SIGNATURE)
|| (!resource.data.starts_with(b"%PDF-")
&& resource.version.path.extension().is_some_and(|extension| {
extension.eq_ignore_ascii_case("jpg") || extension.eq_ignore_ascii_case("jpeg")
}))
}
pub(crate) fn read_jpeg(
resource: LoadedResource,
fallback_resolution: i32,
pdf_version: (i32, i32),
) -> Result<(Self, Option<&'static str>), String> {
let header = jpeg::read(&resource.data).map_err(|error| {
format!(
"could not parse JPEG image {}: {error}",
resource.version.path.display()
)
})?;
if header.progressive && pdf_version.0 == 1 && pdf_version.1 <= 2 {
return Err("cannot use progressive DCT with PDF-1.2".into());
}
let [width, height] = header.size;
let color = match header.components {
1 => "/DeviceGray",
3 => "/DeviceRGB",
4 => "/DeviceCMYK /Decode [1 0 1 0 1 0 1 0]",
_ => unreachable!("JPEG component count was checked"),
};
let mut density = header.density;
let warning = if density.iter().any(|&dpi| dpi > 65_535) {
Some("too large image resolution ignored")
} else if density != [0, 0] && density.contains(&0) {
Some("too small image resolution ignored")
} else {
None
};
if warning.is_some() || density == [0, 0] {
let default = fallback_resolution.clamp(0, 65_535) as u32;
density = [if default == 0 { 72 } else { default }; 2];
}
let natural = std::array::from_fn(|axis| {
// One hundred inches in TeX scaled points.
let numerator = 473_628_672_i64 * i64::from(header.size[axis]);
let denominator = 100 * i64::from(density[axis]);
(numerator + denominator / 2) / denominator
});
let dictionary = format!(
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace {color} /BitsPerComponent {} /Filter /DCTDecode /Length {} >>\nstream\n",
header.precision,
resource.data.len()
);
Ok((
Self {
version: resource.version,
page: 1,
page_count: 1,
natural,
extent: [1.0_f64.to_bits(); 2],
objects: vec![vec![
Part::Bytes(dictionary.into_bytes()),
Part::Jpeg {
size: header.size,
precision: header.precision,
bytes: resource.data,
},
Part::Bytes(b"\nendstream".to_vec()),
]],
},
warning,
))
}
pub(crate) fn jpeg_frame(&self) -> Option<([u16; 2], u8)> {
self.objects.first()?.iter().find_map(|part| match part {
Part::Jpeg {
size, precision, ..
} => Some((*size, *precision)),
_ => None,
})
}
pub(crate) fn read(
resource: LoadedResource,
page: usize,
@@ -172,12 +266,12 @@ impl PdfImage {
),
_ => return Err("PDF image rotation must be a multiple of 90 degrees".into()),
};
let sp = |bp: f64| -> Result<i32, String> {
let sp = |bp: f64| -> Result<i64, String> {
let value = (bp * 65536.0 * 803.0 / 800.0).round();
if !(1.0..=1073741823.0).contains(&value) {
return Err("invalid image dimensions".into());
}
Ok(value as i32)
Ok(value as i64)
};
let natural = [sp(width)?, sp(height)?];
let mut contents = Vec::new();
@@ -243,7 +337,7 @@ impl PdfImage {
}
for part in parts {
match part {
Part::Bytes(bytes) => body.extend_from_slice(bytes),
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(),
}
}