Render native XeTeX PNG, JPEG and BMP graphics
This commit is contained in:
1 parent
794c2f9b2c
commit
2bd6e19519
22 files changed
+821
-120
No files matched your search
@@ -0,0 +1,254 @@
|
||||
//! The xdvipdfmx raster image device special.
|
||||
use super::Affine;
|
||||
use crate::pdf_image::{PdfImage, PdfImageUse, real};
|
||||
use lopdf::{Object, content::Content};
|
||||
use std::{iter::Peekable, str::SplitAsciiWhitespace, sync::Arc};
|
||||
|
||||
pub(crate) struct ImageSpecial {
|
||||
pub file: String,
|
||||
pub attributes: Vec<u8>,
|
||||
pub hidden: bool,
|
||||
bbox: Option<[f64; 4]>,
|
||||
dimensions: [Option<f64>; 3],
|
||||
transform: Affine,
|
||||
clip: bool,
|
||||
}
|
||||
|
||||
impl ImageSpecial {
|
||||
pub(crate) fn parse(data: &[u8], magnification: i32) -> Result<Option<Self>, String> {
|
||||
let Some(body) = data.trim_ascii_start().strip_prefix(b"pdf:") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let body = body.trim_ascii_start();
|
||||
let name_end = body
|
||||
.iter()
|
||||
.position(|byte| byte.is_ascii_whitespace() || matches!(byte, b'(' | b'<'))
|
||||
.unwrap_or(body.len());
|
||||
if !matches!(&body[..name_end], b"image" | b"img") {
|
||||
return Ok(None);
|
||||
}
|
||||
let body = &body[name_end..];
|
||||
let file_pos = body
|
||||
.iter()
|
||||
.position(|byte| matches!(byte, b'(' | b'<'))
|
||||
.ok_or("missing XDV image filename string")?;
|
||||
let parameters =
|
||||
std::str::from_utf8(&body[..file_pos]).map_err(|error| error.to_string())?;
|
||||
let mut words = parameters.split_ascii_whitespace().peekable();
|
||||
let mut bbox = None;
|
||||
let mut dimensions = [None; 3];
|
||||
let mut clip = true;
|
||||
let mut hidden = false;
|
||||
let mut scales = [None; 2];
|
||||
let mut overall_scale = None;
|
||||
let mut rotation = 0.0;
|
||||
let mut matrix = None;
|
||||
while let Some(parameter) = words.next() {
|
||||
match parameter {
|
||||
"bbox" => {
|
||||
bbox = Some([
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
]);
|
||||
}
|
||||
"width" => dimensions[0] = Some(length(&mut words, magnification)?),
|
||||
"height" => dimensions[1] = Some(length(&mut words, magnification)?),
|
||||
"depth" => dimensions[2] = Some(length(&mut words, magnification)?),
|
||||
"scale" => overall_scale = Some(number(words.next())?),
|
||||
"xscale" => scales[0] = Some(number(words.next())?),
|
||||
"yscale" => scales[1] = Some(number(words.next())?),
|
||||
"rotate" => rotation = number(words.next())?,
|
||||
"matrix" => {
|
||||
matrix = Some(Affine([
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
number(words.next())?,
|
||||
]));
|
||||
}
|
||||
"clip" => clip = number(words.next())? != 0.0,
|
||||
"hide" => hidden = true,
|
||||
"page" if matches!(number(words.next())?, 0.0 | 1.0) => {}
|
||||
_ => return Err(format!("unsupported XDV raster image option {parameter}")),
|
||||
}
|
||||
}
|
||||
if overall_scale.is_some() && scales.iter().any(Option::is_some) {
|
||||
return Err("XDV image scale conflicts with an axis scale".into());
|
||||
}
|
||||
if dimensions[0].is_some() && scales[0].is_some() {
|
||||
scales[0] = None;
|
||||
} else if (dimensions[1].is_some() || dimensions[2].is_some()) && scales[1].is_some() {
|
||||
scales[1] = None;
|
||||
}
|
||||
let [sx, sy] = scales.map(|value| value.or(overall_scale).unwrap_or(1.0));
|
||||
let (sin, cos) = rotation.to_radians().sin_cos();
|
||||
let transform =
|
||||
matrix.unwrap_or(Affine([cos * sx, sin * sx, -sin * sy, cos * sy, 0.0, 0.0]));
|
||||
|
||||
// The suffix shares the PDF string and dictionary grammar. Decode
|
||||
// the objects with the same parser used for native page resources.
|
||||
let mut pdf_objects = body[file_pos..].to_vec();
|
||||
pdf_objects.extend_from_slice(b"\nq");
|
||||
let parsed = Content::decode(&pdf_objects).map_err(|error| error.to_string())?;
|
||||
let [operation] = parsed.operations.as_slice() else {
|
||||
return Err("invalid PDF objects in XDV image special".into());
|
||||
};
|
||||
let (file, dictionary) = match operation.operands.as_slice() {
|
||||
[Object::String(file, _)] if operation.operator == "q" => (file, None),
|
||||
[Object::String(file, _), Object::Dictionary(dict)] if operation.operator == "q" => {
|
||||
(file, Some(dict))
|
||||
}
|
||||
_ => {
|
||||
return Err("expected filename and optional XDV image attribute dictionary".into());
|
||||
}
|
||||
};
|
||||
let file = String::from_utf8(file.clone()).map_err(|error| error.to_string())?;
|
||||
let mut attributes = Vec::new();
|
||||
if let Some(dictionary) = dictionary {
|
||||
for (key, value) in dictionary.iter() {
|
||||
match (key.as_slice(), value) {
|
||||
(b"Decode", Object::Array(values)) => {
|
||||
if values.is_empty() || values.len() % 2 != 0 {
|
||||
return Err("XDV image Decode array requires pairs".into());
|
||||
}
|
||||
attributes.extend_from_slice(b"/Decode [");
|
||||
for value in values {
|
||||
let number = match value {
|
||||
Object::Integer(value) => *value as f64,
|
||||
Object::Real(value) if value.is_finite() => *value,
|
||||
_ => {
|
||||
return Err(
|
||||
"XDV image Decode array requires finite numbers".into()
|
||||
);
|
||||
}
|
||||
};
|
||||
attributes.extend_from_slice(real(number).as_bytes());
|
||||
attributes.push(b' ');
|
||||
}
|
||||
attributes.extend_from_slice(b"] ");
|
||||
}
|
||||
(b"Interpolate", Object::Boolean(value)) => {
|
||||
attributes.extend_from_slice(if *value {
|
||||
b"/Interpolate true "
|
||||
} else {
|
||||
b"/Interpolate false "
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"unsupported XDV image attribute {}",
|
||||
String::from_utf8_lossy(key)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(Self {
|
||||
file,
|
||||
attributes,
|
||||
hidden,
|
||||
bbox,
|
||||
dimensions,
|
||||
transform,
|
||||
clip,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn place(&self, id: usize, image: Arc<PdfImage>) -> Result<PdfImageUse, String> {
|
||||
let [natural_w, natural_h] = image.extent();
|
||||
let ([pixels_w, pixels_h], _) = image
|
||||
.raster_frame()
|
||||
.ok_or("XDV special needs a raster image")?;
|
||||
let [left, bottom, right, top] = self.bbox.unwrap_or([0.0, 0.0, natural_w, natural_h]);
|
||||
let [box_w, box_h] = [right - left, top - bottom];
|
||||
if box_w <= 0.0 || box_h <= 0.0 {
|
||||
return Err("XDV image bounding box must have positive dimensions".into());
|
||||
}
|
||||
let [requested_w, requested_h, depth] = self.dimensions;
|
||||
let requested_h = requested_h.or(depth.map(|_| 0.0));
|
||||
let depth = depth.unwrap_or(0.0);
|
||||
let [xscale, yscale] = [natural_w / box_w, natural_h / box_h];
|
||||
let pixel_aspect = pixels_w as f64 / pixels_h as f64;
|
||||
let (width, height, depth) = match (requested_w, requested_h) {
|
||||
(Some(w), Some(h)) => (w * xscale, (h + depth) * yscale, depth * yscale),
|
||||
(Some(w), None) => (w * xscale, w * xscale / pixel_aspect, 0.0),
|
||||
(None, Some(h)) => (
|
||||
(h + depth) * yscale * pixel_aspect,
|
||||
(h + depth) * yscale,
|
||||
depth * yscale,
|
||||
),
|
||||
(None, None) => (box_w, box_h, 0.0),
|
||||
};
|
||||
let sizing = Affine([
|
||||
width,
|
||||
0.0,
|
||||
0.0,
|
||||
height,
|
||||
-left * width / natural_w,
|
||||
-bottom * height / natural_h - depth,
|
||||
]);
|
||||
let clip = (self.clip && self.bbox.is_some()).then_some([
|
||||
left / natural_w,
|
||||
bottom / natural_h,
|
||||
box_w / natural_w,
|
||||
box_h / natural_h,
|
||||
]);
|
||||
PdfImageUse::new_xdv_raster_special(id, image, self.transform.concatenate(sizing), clip)
|
||||
}
|
||||
}
|
||||
|
||||
fn number(word: Option<&str>) -> Result<f64, &'static str> {
|
||||
word.and_then(|word| word.parse::<f64>().ok())
|
||||
.filter(|value| value.is_finite())
|
||||
.ok_or("invalid XDV image number")
|
||||
}
|
||||
|
||||
fn length(
|
||||
words: &mut Peekable<SplitAsciiWhitespace<'_>>,
|
||||
magnification: i32,
|
||||
) -> Result<f64, &'static str> {
|
||||
let word = words.next().ok_or("missing XDV image length")?;
|
||||
let split = word
|
||||
.bytes()
|
||||
.position(|byte| byte.is_ascii_alphabetic())
|
||||
.unwrap_or(word.len());
|
||||
let (value, mut unit) = word.split_at(split);
|
||||
let value = number(Some(value))?;
|
||||
if unit.is_empty() && words.peek().is_some_and(|word| is_unit(word)) {
|
||||
unit = words.next().unwrap();
|
||||
}
|
||||
let mut factor = 1.0;
|
||||
if let Some(rest) = unit.strip_prefix("true") {
|
||||
unit = if rest.is_empty() {
|
||||
words.next().ok_or("missing XDV image unit")?
|
||||
} else {
|
||||
rest
|
||||
};
|
||||
factor *= 1000.0 / f64::from(magnification);
|
||||
}
|
||||
factor *= match unit {
|
||||
"pt" => 800.0 / 803.0,
|
||||
"in" => 72.0,
|
||||
"cm" => 72.0 / 2.54,
|
||||
"mm" => 72.0 / 25.4,
|
||||
"" | "bp" => 1.0,
|
||||
"pc" => 12.0 * 800.0 / 803.0,
|
||||
"dd" => 1238.0 / 1157.0 * 800.0 / 803.0,
|
||||
"cc" => 12.0 * 1238.0 / 1157.0 * 800.0 / 803.0,
|
||||
"sp" => 800.0 / 803.0 / 65536.0,
|
||||
_ => return Err("invalid XDV image length unit"),
|
||||
};
|
||||
Ok(value * factor)
|
||||
}
|
||||
|
||||
fn is_unit(word: &str) -> bool {
|
||||
word == "true"
|
||||
|| matches!(
|
||||
word.strip_prefix("true").unwrap_or(word),
|
||||
"pt" | "in" | "cm" | "mm" | "bp" | "pc" | "dd" | "cc" | "sp"
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user