Fit RTF pictures within page bounds and report omitted media

This commit is contained in:
Dylan M. Taylor committed 2026-11-18 14:57:09 -05:00
1 parent 1cd10fb9b2
commit ac8c44517d
6 files changed
+86 -12

No files matched your search

+10 -3
View File
@@ -197,7 +197,8 @@ pub struct OfficeExport {
/// Pages (0-based) that draw forms nested deeper than [`MAX_FORM_DEPTH`] or more of them
/// than [`MAX_FORM_VISITS`], or pictures past [`MAX_EXPORT_IMAGE_BYTES`] or past what one export
/// may decode: export stops reading there to stay bounded on hostile files, so the text and images of those forms, or
/// those pictures, are missing from `bytes`.
/// those pictures, are missing from `bytes`. RTF also reports pages whose pictures could
/// not be encoded or fit its output/raster budgets; remaining page content is preserved.
pub truncated_pages: Vec<usize>,
}
@@ -330,7 +331,7 @@ impl crate::Document {
/// ([`OfficeExport::truncated_pages`]).
pub fn export_office_checked(&self, format: OfficeFormat) -> OfficeExport {
// Markdown leaves pictures out.
let (pages, truncated_pages) = self.export_pages_checked(!matches!(format, OfficeFormat::Markdown), MAX_EXPORT_IMAGE_BYTES);
let (pages, mut truncated_pages) = self.export_pages_checked(!matches!(format, OfficeFormat::Markdown), MAX_EXPORT_IMAGE_BYTES);
let title = self.info.title.clone().unwrap_or_else(|| self.name.trim_end_matches(".pdf").to_string());
// Word and HTML name the document's language (`/Lang`), so spelling is checked in it.
let language = self.initial_view().language;
@@ -339,7 +340,13 @@ impl crate::Document {
OfficeFormat::Pptx => pdfcraft_export::pptx(&pages, &title),
OfficeFormat::Html => pdfcraft_export::html_with_language(&pages, &title, language.as_deref()).into_bytes(),
OfficeFormat::HtmlSimple => pdfcraft_export::html_simple_with_language(&pages, &title, language.as_deref()).into_bytes(),
OfficeFormat::Rtf => pdfcraft_export::rtf_with_title(&pages, &title).into_bytes(),
OfficeFormat::Rtf => {
let (rtf, omitted) = pdfcraft_export::rtf_with_title_checked(&pages, &title);
truncated_pages.extend(omitted);
truncated_pages.sort_unstable();
truncated_pages.dedup();
rtf.into_bytes()
}
OfficeFormat::Markdown => pdfcraft_export::markdown(&pages).into_bytes(),
};
OfficeExport { bytes, truncated_pages }
+8
View File
@@ -21,3 +21,11 @@ pub fn rtf(pages: &[Page]) -> String {
pub fn rtf_with_title(pages: &[Page], title: &str) -> String {
craft_rtf::doc::export_with_generator(&flow_doc(pages, &Meta { title, language: None, font: FONT }), GENERATOR)
}
/// RTF plus zero-based pages where nonempty pictures could not be embedded. Page text and
/// other surviving content are retained; this is partial-output reporting, not a page drop.
pub fn rtf_with_title_checked(pages: &[Page], title: &str) -> (String, Vec<usize>) {
let mut omitted = Vec::new();
let doc = super::as_word::flow_doc_with_omissions(pages, &Meta { title, language: None, font: FONT }, &mut omitted);
(craft_rtf::doc::export_with_generator(&doc, GENERATOR), omitted)
}
+19 -6
View File
@@ -42,7 +42,7 @@ fn push_text(p: &mut Paragraph, text: &str, props: CharProps) {
fn table(t: &Table) -> craft_wordmodel::Table {
let mut edges = t.cols.clone();
edges.push(t.rect[2]);
// Whole twips, at least 3 pt wide (Word's narrowest column), as `as_docx` writes them.
// Whole twips, at least 20 pt wide before the Word-range clamp, as `as_docx` writes them.
let widths: Vec<f32> = edges.windows(2).map(|w| (((w[1] - w[0]).max(20.0) * 20.0).round().clamp(60.0, 31680.0) / 20.0) as f32).collect();
let [top, left, bottom, right] = t.ruled.unwrap_or_default();
let inside = t.ruled.is_some();
@@ -138,7 +138,8 @@ fn styles(font: &str, language: Option<&str>) -> StyleSheet {
fn picture(doc: &mut Document, im: &Image, bytes: Vec<u8>, ext: &str, sec: &SectionProps) -> Paragraph {
let text_w = f64::from((sec.page_w - sec.margin_left - sec.margin_right).max(1.0));
let (w, h) = ((im.rect[2] - im.rect[0]).max(1.0), (im.rect[3] - im.rect[1]).max(1.0));
let k = (text_w / w).min(1.0);
let text_h = f64::from((sec.page_h - sec.margin_top - sec.margin_bottom).max(1.0));
let k = (text_w / w).min(text_h / h).min(1.0);
let media = doc.add_media(bytes, ext);
let mut p = Paragraph::new();
p.push_object(
@@ -169,10 +170,14 @@ pub(crate) struct Meta<'a> {
/// The pages as one flowing document: each page a section of its own size (so a page always
/// starts a new one, blank pages included), its paragraphs, tables and pictures in reading order.
pub(crate) fn flow_doc(pages: &[Page], meta: &Meta) -> Document {
flow_doc_with_budget(pages, meta, pictures::Budget::default())
flow_doc_with_omissions(pages, meta, &mut Vec::new())
}
fn flow_doc_with_budget(pages: &[Page], meta: &Meta, mut pictures: pictures::Budget) -> Document {
pub(crate) fn flow_doc_with_omissions(pages: &[Page], meta: &Meta, omitted: &mut Vec<usize>) -> Document {
flow_doc_with_budget(pages, meta, pictures::Budget::default(), omitted)
}
fn flow_doc_with_budget(pages: &[Page], meta: &Meta, mut pictures: pictures::Budget, omitted: &mut Vec<usize>) -> Document {
let mut doc = Document::new();
doc.styles = std::sync::Arc::new(styles(meta.font, meta.language));
doc.core.title = meta.title.to_string();
@@ -200,10 +205,18 @@ fn flow_doc_with_budget(pages: &[Page], meta: &Meta, mut pictures: pictures::Bud
body.push(Block::Table(table(&t)));
}
Item::Img(im) => {
if im.bytes.is_empty() || media >= MAX_MEDIA {
if im.bytes.is_empty() {
continue;
}
let Some((bytes, ext)) = pictures.prepare(im) else { continue };
let prepared = (media < MAX_MEDIA).then(|| pictures.prepare(im)).flatten();
let Some((bytes, ext)) = prepared else {
// Keep readable page content, but tell checked callers which pages lost
// pictures to encoding, transform, or resource limits.
if omitted.last() != Some(&page) {
omitted.push(page);
}
continue;
};
media += 1;
body.push(Block::Para(picture(&mut doc, im, bytes, ext, &sec)));
}
+33 -2
View File
@@ -63,10 +63,12 @@ impl Budget {
if output_pixels > MAX_PIXELS {
return None;
}
self.raster = self.raster.checked_add(pixels)?.checked_add(output_pixels)?;
if self.raster > MAX_RASTER_WORK {
let raster = self.raster.checked_add(pixels)?.checked_add(output_pixels)?;
if raster > MAX_RASTER_WORK {
return None;
}
// Charge only accepted work, but retain the charge if decoding later fails.
self.raster = raster;
let mut limits = image::Limits::default();
limits.max_image_width = Some(4096);
limits.max_image_height = Some(4096);
@@ -201,11 +203,14 @@ mod tests {
let im = sample(0.0);
let cost = rtf_bytes(im.bytes.len()).expect("small");
let page = crate::layout::Page { width: 10.0, height: 10.0, blocks: Vec::new(), images: vec![im; 3], background: None, rules: Vec::new() };
let mut omitted = Vec::new();
let doc = super::super::flow_doc_with_budget(
&[page],
&super::super::Meta { title: "", language: None, font: "Helvetica" },
Budget { encoded: MAX_ENCODED - 2 * cost, raster: 0 },
&mut omitted,
);
assert_eq!(omitted, [0]);
let count: usize = doc
.body
.iter()
@@ -219,6 +224,32 @@ mod tests {
assert_eq!(rtf.matches("\\pngblip").count(), 2);
}
#[test]
fn rejected_raster_charge_leaves_room_for_a_smaller_picture() {
let mut budget = Budget { encoded: 0, raster: MAX_RASTER_WORK - 4 };
assert!(budget.prepare(&sample(45.0)).is_none());
assert_eq!(budget.raster, MAX_RASTER_WORK - 4);
assert!(budget.prepare(&sample(90.0)).is_some());
assert_eq!(budget.raster, MAX_RASTER_WORK);
}
#[test]
fn picture_fits_both_text_area_dimensions() {
let mut im = sample(0.0);
im.rect = [0.0, 0.0, 100.0, 1000.0];
let section = craft_wordmodel::SectionProps {
page_w: 600.0,
page_h: 400.0,
margin_top: 50.0,
margin_bottom: 50.0,
margin_left: 50.0,
margin_right: 50.0,
..Default::default()
};
let p = super::super::picture(&mut craft_wordmodel::Document::new(), &im, im.bytes.to_vec(), im.ext, &section);
assert!(matches!(p.objects.first(), Some(craft_wordmodel::InlineObject::Image { w, h, .. }) if *w == 30.0 && *h == 300.0));
}
#[test]
fn raster_work_and_encoded_writer_are_bounded() {
assert!(Budget { encoded: 0, raster: MAX_RASTER_WORK }.prepare(&sample(45.0)).is_none());
+1 -1
View File
@@ -36,7 +36,7 @@ pub use as_html::{html, html_simple, html_simple_with_language, html_with_langua
pub use as_markdown::markdown;
#[cfg(test)]
use as_markdown::{emphasis, paragraph};
pub use as_rtf::{rtf, rtf_with_title};
pub use as_rtf::{rtf, rtf_with_title, rtf_with_title_checked};
pub use clip::{ClipBuilder, ClipSpan, ClipStyle, ClipText, MAX_CLIP_HTML_BYTES, MAX_CLIP_SPANS, MAX_CLIP_TEXT_BYTES, clip_html, font_family};
#[cfg(test)]
use flow::list_item;
+15
View File
@@ -1578,3 +1578,18 @@ fn html_bounds_the_pictures_it_embeds() {
assert_eq!(h.matches("<img").count(), MAX_MEDIA);
}
}
#[test]
fn checked_rtf_reports_omitted_pictures_once_per_page_without_dropping_text() {
let mut first = page();
first.images[0].rotation = f64::NAN;
first.images.push(first.images[0].clone());
let clean = page();
let mut third = first.clone();
third.blocks[0].text = "Surviving last-page text".into();
let pages = [first, clean, third];
let (output, omitted) = crate::rtf_with_title_checked(&pages, "Partial");
assert_eq!(omitted, [0, 2]);
assert!(output.contains("Surviving last-page text"));
assert_eq!(output, crate::rtf_with_title(&pages, "Partial"));
}