Embed image XObjects in route-D PDF output

This commit is contained in:
gloamxun committed 2026-10-20 18:13:33 +08:00
1 parent 7dd3961e21
commit 431bbd14d4
3 files changed
+169 -34

No files matched your search

+28
View File
@@ -1333,6 +1333,34 @@ mod tests {
assert!(text.contains("/Count 2"));
assert_eq!(text.matches("/Type /Page ").count(), 2);
}
#[test]
fn image_xobject_is_embedded_and_painted() {
use crate::render::{DisplayItem, DisplayList, PdfImage};
let mut list = DisplayList {
width: 612 * 65_536,
height: 792 * 65_536,
items: Vec::new(),
images: Vec::new(),
};
let index = list.add_image(PdfImage {
width: 1,
height: 1,
rgb: vec![255, 0, 0],
});
list.push(DisplayItem::Image {
x: 0,
y: 0,
width: 10 * 65_536,
height: 10 * 65_536,
index,
});
let pdf = crate::pdf::display_list_to_pdf(&list, 792 * 65_536);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/Subtype /Image"));
assert!(text.contains("/XObject << /Im0"));
assert!(text.contains("/Im0 Do"));
}
#[test]
fn display_list_writes_a_minimal_pdf() {
let document = Document::new(400, vec![Unit::paragraph(1, "hello")]);
+100 -34
View File
@@ -1,8 +1,9 @@
//! Minimal PDF writer for route-D display lists.
//!
//! Base-14 Times-Roman text and filled rectangles only. This is the
//! structural backend: multi-page output is supported; TFM/NFSS fonts,
//! XObjects and `\special` are later milestones.
//! Base-14 Times-Roman text, filled rectangles, and raw-RGB image XObjects.
//! TFM/NFSS fonts and `\special` are later milestones.
use std::collections::BTreeMap;
use crate::render::{DisplayItem, DisplayList};
@@ -24,7 +25,7 @@ fn pt(value: i64) -> String {
format!("{:.3}", value as f64 / 65_536.0)
}
fn page_content(list: &DisplayList, page_height: i64, height: i64) -> String {
fn page_content(list: &DisplayList, height: i64, image_names: &BTreeMap<usize, String>) -> String {
let mut content = String::from("q\n0 0 0 rg\n");
for item in &list.items {
match item {
@@ -51,10 +52,26 @@ fn page_content(list: &DisplayList, page_height: i64, height: i64) -> String {
pt(*rule_height)
));
}
DisplayItem::Image {
x,
y,
width,
height: image_height,
index,
} => {
if let Some(name) = image_names.get(index) {
content.push_str(&format!(
"q {} 0 0 {} {} {} cm /{name} Do Q\n",
pt(*width),
pt(*image_height),
pt(*x),
pt(height - *y - *image_height)
));
}
}
}
}
content.push_str("Q\n");
let _ = page_height;
content
}
@@ -68,54 +85,103 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8>
.unwrap_or(612 * 65_536)
.max(612 * 65_536);
let mut objects: Vec<String> = Vec::new();
objects.push("<< /Type /Catalog /Pages 2 0 R >>".to_string());
objects.push(String::new()); // pages object filled below
objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>".to_string());
let mut objects: Vec<Vec<u8>> = Vec::new();
objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());
objects.push(Vec::new()); // pages object filled below
objects.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>".to_vec());
let mut kids = Vec::new();
for list in pages {
let mut used = BTreeMap::new();
for item in &list.items {
if let DisplayItem::Image { index, .. } = item {
let next = used.len();
used.entry(*index).or_insert(next);
}
}
let page_id = objects.len() + 1;
let content_id = page_id + 1;
let image_base = content_id + 1;
let xobjects = used
.iter()
.map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot))
.collect::<Vec<_>>()
.join(" ");
let resources = if used.is_empty() {
"<< /Font << /F1 3 0 R >> >>".to_string()
} else {
format!("<< /Font << /F1 3 0 R >> /XObject << {xobjects} >> >>")
};
kids.push(format!("{page_id} 0 R"));
objects.push(format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources << /Font << /F1 3 0 R >> >> /Contents {content_id} 0 R >>",
pt(width),
pt(height)
));
let content = page_content(list, page_height, height);
objects.push(format!(
"<< /Length {} >>\nstream\n{}endstream",
content.len(),
content
));
objects.push(
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources {resources} /Contents {content_id} 0 R >>",
pt(width),
pt(height)
)
.into_bytes(),
);
let mut names = BTreeMap::new();
for (index, slot) in &used {
names.insert(*index, format!("Im{slot}"));
}
let content = page_content(list, height, &names);
objects.push(
format!(
"<< /Length {} >>\nstream\n{}endstream",
content.len(),
content
)
.into_bytes(),
);
for (index, _) in &used {
let image = &list.images[*index];
let mut object = format!(
"<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Length {} >>\nstream\n",
image.width,
image.height,
image.rgb.len()
)
.into_bytes();
object.extend_from_slice(&image.rgb);
object.extend_from_slice(b"\nendstream");
objects.push(object);
}
}
objects[1] = format!(
"<< /Type /Pages /Kids [{}] /Count {} >>",
kids.join(" "),
pages.len()
);
)
.into_bytes();
let mut pdf = String::from("%PDF-1.4\n");
let mut pdf: Vec<u8> = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for (index, object) in objects.iter().enumerate() {
offsets.push(pdf.len());
pdf.push_str(&format!("{} 0 obj\n{}\nendobj\n", index + 1, object));
pdf.extend_from_slice(format!("{} 0 obj\n", index + 1).as_bytes());
pdf.extend_from_slice(object);
pdf.extend_from_slice(b"\nendobj\n");
}
let xref = pdf.len();
pdf.push_str(&format!(
"xref\n0 {}\n0000000000 65535 f \n",
objects.len() + 1
));
pdf.extend_from_slice(
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
);
for offset in &offsets {
pdf.push_str(&format!("{:010} 00000 n \n", offset));
pdf.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
}
pdf.push_str(&format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
xref
));
pdf.into_bytes()
pdf.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
xref
)
.as_bytes(),
);
pdf
}
/// Write one page; kept for the single-page spike and tests.
+41
View File
@@ -24,6 +24,21 @@ pub enum DisplayItem {
width: i64,
height: i64,
},
Image {
x: i64,
y: i64,
width: i64,
height: i64,
index: usize,
},
}
/// A raw RGB image that can be painted as a PDF XObject.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PdfImage {
pub width: u32,
pub height: u32,
pub rgb: Vec<u8>,
}
/// A page-local list of drawing primitives.
@@ -32,6 +47,7 @@ pub struct DisplayList {
pub width: i64,
pub height: i64,
pub items: Vec<DisplayItem>,
pub images: Vec<PdfImage>,
}
impl DisplayList {
@@ -39,6 +55,11 @@ impl DisplayList {
self.items.push(item);
}
pub fn add_image(&mut self, image: PdfImage) -> usize {
self.images.push(image);
self.images.len() - 1
}
/// Offset every primitive, used when placing a nested table on a page.
pub fn place(&mut self, dx: i64, dy: i64) {
for item in &mut self.items {
@@ -51,6 +72,10 @@ impl DisplayList {
*x += dx;
*y += dy;
}
DisplayItem::Image { x, y, .. } => {
*x += dx;
*y += dy;
}
}
}
}
@@ -87,6 +112,21 @@ impl DisplayList {
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"black\"/>\n"
));
}
DisplayItem::Image {
x,
y,
width,
height,
..
} => {
let x = *x as f64 / 65_536.0;
let y = *y as f64 / 65_536.0;
let width = *width as f64 / 65_536.0;
let height = *height as f64 / 65_536.0;
out.push_str(&format!(
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"#cccccc\"/>\n"
));
}
}
}
out.push_str("</svg>\n");
@@ -108,6 +148,7 @@ impl Halign {
width: self.width,
height: self.height,
items: Vec::new(),
images: Vec::new(),
};
let mut y = 0_i64;
for (row_index, row) in self.rows.iter().enumerate() {