Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M14: JPEG and TIFF export refuse a raster of the wrong length instead of panicking

Grzegorz Martens87648be1cddf
diff --git a/ROADMAP.md b/ROADMAP.md
index 49a8b27cc..6179fee2e 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -220,6 +220,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-12 (gap 6, #1319, #1305, #1324):** Editing an XFA form keeps a radio item's stored text when it contains a space, so a later layout still selects it. Replace Pages on a split selection replaces those pages and leaves the gap; editing the dialog range still replaces the span. Marking a figure decorative rewrites only that figure's content stream, so a header, added text and unknown stream entries stay. Estimates unchanged.
- **2026-10-15 (M14, gap 24):** `misc.localization` and `misc.installers` move from planned to partial. Localization: 22 catalogs ship, but Chinese shows tofu in releases, Telugu has no release font and Arabic is not mirrored. Installers: macOS and Windows releases are signed, Linux packages are not. The Acrobat menu diff itself remains open. Estimates unchanged.
- **2026-10-15 (M14, PNG export):** Export ▸ Image as PNG, `pdfcraft-cli render` and the `page_render` automation/MCP tool write an opaque page as RGB at deflate level 3 instead of RGBA at the default level 6: the files stay the same size and are written 3–5× faster (a 300-dpi scan drawn at 220 dpi: 805 → 167 ms; a text page at 220 dpi: 70 → 40 ms; an annual-report page at 150 dpi: 179 → 64 ms). A page with translucent pixels is still written as RGBA. The automation tools use the engine's encoder instead of a copy of it. Estimates unchanged.
+- **2026-10-22 (M14, JPEG and TIFF export):** Export ▸ Image as JPEG or TIFF refuses a raster that is not exactly width × height pixels, as PNG export has since #2425. A raster a pixel short panicked inside the JPEG and TIFF encoders, and a partial pixel at the end was dropped and the rest written as a valid image. Rendered pages are always the right size, so what exports is unchanged. Estimates unchanged.
- **2026-10-13 (G14, Vietnamese localization):** Added Vietnamese (`vi`, Tiếng Việt) as an interface and date language with a 2,591-entry catalog (`plural_none`) covering 100% of the current localizable key union (plus `theme`/`Appearance`). Locale tags `vi` / `vi-VN` / `vi_VN.UTF-8` resolve; calendar months use numeric `Tháng 1`…`12` / `tháng 1`…`12`. Native-speaker community review recorded. The twelve-language localization mean moves from ≈59% to ≈68%; weighted readiness ≈49% → ≈50%. Status stays `partial`: engine/OS details, document contents, filenames, CLI/MCP and external help stay outside the catalog by design.
- **2026-10-13 (M3, typed zoom):** The right rail's zoom percentage is an editable field: type 150, 150% or 62.5 % and press Enter, Escape discards, and nonsense keeps the current zoom. The control channel's zoom option shares its parser, which now refuses zero, negative and non-finite values.
diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs
index a1820e2d9..d07531a8d 100644
--- a/crates/engine/src/export.rs
+++ b/crates/engine/src/export.rs
@@ -147,15 +147,7 @@ pub fn encode_image(width: u32, height: u32, premultiplied: &[u8], format: Image
/// (4.46 → 4.47 MB), a text page at 220 dpi 70 → 40 ms (0.85 → 0.89 MB), and an annual
/// report page at 150 dpi 179 → 64 ms (1.41 → 1.38 MB).
pub fn encode_png(width: u32, height: u32, premultiplied: &[u8]) -> Result<Vec<u8>, String> {
- // Checked here, not left to the encoder: `as_chunks` below drops a partial trailing pixel,
- // and the opaque path would write the rest as a valid image.
- let expected = usize::try_from(width).ok().zip(usize::try_from(height).ok()).and_then(|(w, h)| w.checked_mul(h)?.checked_mul(4));
- if expected != Some(premultiplied.len()) {
- return Err(match expected {
- Some(n) => format!("a {width}×{height} raster is {n} bytes of RGBA, got {}", premultiplied.len()),
- None => format!("a {width}×{height} raster is too large"),
- });
- }
+ check_raster(width, height, premultiplied)?;
let pixels = premultiplied.as_chunks::<4>().0;
let opaque = pixels.iter().all(|px| px[3] == 255);
let (color, data) = if opaque {
@@ -213,6 +205,18 @@ impl ImageFormat {
}
}
+/// Checks that `premultiplied` is exactly `width × height` RGBA pixels, before any encoder
+/// sees it: `as_chunks` drops a partial trailing pixel, so the rest would be written as a valid
+/// image, and the JPEG and TIFF encoders panic on a buffer that doesn't fit the size.
+fn check_raster(width: u32, height: u32, premultiplied: &[u8]) -> Result<(), String> {
+ let expected = usize::try_from(width).ok().zip(usize::try_from(height).ok()).and_then(|(w, h)| w.checked_mul(h)?.checked_mul(4));
+ match expected {
+ Some(n) if n == premultiplied.len() => Ok(()),
+ Some(n) => Err(format!("a {width}×{height} raster is {n} bytes of RGBA, got {}", premultiplied.len())),
+ None => Err(format!("a {width}×{height} raster is too large")),
+ }
+}
+
/// Premultiplied RGBA composited over white → RGB.
fn over_white(premultiplied: &[u8]) -> Vec<u8> {
premultiplied
@@ -230,6 +234,7 @@ fn over_white(premultiplied: &[u8]) -> Vec<u8> {
pub fn encode_jpeg(width: u32, height: u32, premultiplied: &[u8], quality: u8, dpi: f64) -> Result<Vec<u8>, String> {
use image::ImageEncoder;
use image::codecs::jpeg::{JpegEncoder, PixelDensity};
+ check_raster(width, height, premultiplied)?;
let rgb = over_white(premultiplied);
let mut out = Vec::new();
let mut enc = JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100));
@@ -246,6 +251,7 @@ pub fn encode_tiff(width: u32, height: u32, premultiplied: &[u8], dpi: f64) -> R
use tiff::encoder::{Compression, Rational, TiffEncoder, colortype::RGB8};
use tiff::tags::{ResolutionUnit, Tag};
let err = |e: tiff::TiffError| e.to_string();
+ check_raster(width, height, premultiplied)?;
let rgb = over_white(premultiplied);
let mut out = std::io::Cursor::new(Vec::new());
let mut tiff = TiffEncoder::new(&mut out).map_err(err)?.with_compression(Compression::Lzw);
@@ -287,8 +293,10 @@ mod image_name_tests {
}
#[cfg(test)]
-mod png_tests {
- use super::encode_png;
+mod raster_tests {
+ use super::{ImageFormat, encode_image, encode_png};
+
+ const FORMATS: [ImageFormat; 3] = [ImageFormat::Png, ImageFormat::Jpeg { quality: 90 }, ImageFormat::Tiff];
/// The colour type and pixels of a PNG.
fn decode(png: &[u8]) -> (png::ColorType, Vec<u8>) {
@@ -318,8 +326,9 @@ mod png_tests {
assert_eq!(pixels, [128, 0, 64, 128, 0, 0, 0, 0, 10, 20, 30, 255]);
}
- /// A buffer that is not exactly `width × height` RGBA pixels is an error, opaque or not. The
- /// opaque path used to drop a partial trailing pixel and write the rest as a valid image.
+ /// A buffer that is not exactly `width × height` RGBA pixels is an error in every format,
+ /// opaque or not. A partial trailing pixel used to be dropped and the rest written as a
+ /// valid image, and a buffer too short for its size panicked in the JPEG and TIFF encoders.
#[test]
fn rasters_of_the_wrong_length_are_rejected() {
let cases: [(&str, u32, u32, &[u8]); 7] = [
@@ -331,8 +340,20 @@ mod png_tests {
("empty", 1, 1, &[]),
("a size whose byte count overflows", u32::MAX, u32::MAX, &[10, 20, 30, 255]),
];
- for (what, width, height, data) in cases {
- assert!(encode_png(width, height, data).is_err(), "{what}");
+ for format in FORMATS {
+ for (what, width, height, data) in cases {
+ assert!(encode_image(width, height, data, format, 72.0).is_err(), "{}, {what}", format.label());
+ }
+ }
+ }
+
+ /// A raster of no pixels is the right length, and still an error in every format.
+ #[test]
+ fn rasters_of_no_pixels_are_an_error() {
+ for format in FORMATS {
+ for (width, height) in [(0, 0), (0, 3), (3, 0)] {
+ assert!(encode_image(width, height, &[], format, 72.0).is_err(), "{}, {width}×{height}", format.label());
+ }
}
}
}
diff --git a/docs/roadmap.md b/docs/roadmap.md
index c10d91d20..03b6372f8 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -21,6 +21,7 @@
> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (M3 candidate: native opens retain chosen tools through password retries and defer startup intake while preparation is pending; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (M4 #1310 #1311 #1312: undo, revert and the next save keep the last saved revision; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-15 · **Change:** minor (M14: PNG export writes opaque pages as RGB at deflate level 3, the same size 3–5× faster; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
+> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-10-22 · **Change:** minor (M14: JPEG and TIFF export refuse a raster of the wrong length instead of panicking; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (M3 #1980: exact quit modifiers preserve Ctrl+Alt+Q email input; M3 candidate: native opens retain chosen tools through password retries and defer startup intake while preparation is pending; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (M13: CLI check visits each directory once through aliases and cycles; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (M4: Extract and Split preserve shared Type 3 glyph resources; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
@@ -226,6 +227,7 @@ M2 (renderer), M7 (content editing), M10 (OCR and Office), M11 (Preflight and st
| 2026-10-12 | minor | M1 #1338: a full rewrite keeps unknown trailer entries and objects reachable only from them. Estimates unchanged. |
| 2026-10-12 | minor | M7 #1443: adding a word to a multi-line paragraph keeps its line breaks. Composite subset fonts whose `/W` leaves out default-width glyphs (Chrome, Skia) no longer measure those letters as missing, and paragraphs drawn turned on the page group into rows along their own baselines. Estimates unchanged. |
| 2026-10-15 | minor | M14: PNG export (Export ▸ Image, `pdfcraft-cli render`, `page_render`) writes opaque pages as RGB at deflate level 3: the same file size, 3–5× faster to write. Estimates unchanged. |
+| 2026-10-22 | minor | M14: JPEG and TIFF export (Export ▸ Image) refuse a raster that is not exactly width × height pixels, as PNG export does, instead of panicking in the encoder or dropping a partial pixel. Estimates unchanged. |
| 2026-10-14 | minor | M14: Italian catalog completed (2,528 entries) and dropped from the ≈ 2,000–2,140-entry group; estimates unchanged |
| 2026-10-12 | minor | M4 #1310 #1311 #1312: undo back to the opened file is clean, Revert returns to the last saved file, and the next save keeps that revision. Estimates unchanged. |
| 2026-10-14 | minor | M5: reconciled PR #1457 with upstream main, preserving comment submission shortcuts and upstream roadmap progress. Estimates unchanged. |
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 42bbe8352..3a83b86ab 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -7052,8 +7052,8 @@ milestone = "M10"
status = "shipped"
commands = ["export.image"]
tools = ["doc_export_images"]
-evidence = ["crates/engine/src/tests.rs::pages_export_as_png_jpeg_and_tiff", "crates/automation/tests/automation.rs::exporting_images_and_text_through_tools"]
-notes = "JPEG with quality, TIFF; flattened onto white"
+evidence = ["crates/engine/src/tests.rs::pages_export_as_png_jpeg_and_tiff", "crates/automation/tests/automation.rs::exporting_images_and_text_through_tools", "crates/engine/src/export.rs::rasters_of_the_wrong_length_are_rejected"]
+notes = "JPEG with quality, TIFF; flattened onto white; a raster that is not exactly its width × height in pixels is refused, as for PNG"
[[feature]]
id = "create.export-jpeg2000"