Skip to content

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

M10.3/M10.4: Create from TIFF (every page; 1-bit scans stay 1-bit; resolution from the file), GIF and BMP; opening those converts them. Export pages as JPEG (quality) and TIFF besides PNG, in the dialog and doc_export_images

Brandon Thomas81d0af6c7f29
diff --git a/Cargo.lock b/Cargo.lock
index 8802af85e..a59d8d2e9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -749,6 +749,12 @@ dependencies = [
"bytemuck",
]
+[[package]]
+name = "color_quant"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
+
[[package]]
name = "combine"
version = "4.6.8"
@@ -1515,6 +1521,16 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "gif"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
+dependencies = [
+ "color_quant",
+ "weezl 0.1.12",
+]
+
[[package]]
name = "gl_generator"
version = "0.14.0"
@@ -1945,10 +1961,14 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
+ "color_quant",
+ "gif",
"moxcms",
"num-traits",
"png 0.18.1",
"tiff",
+ "zune-core",
+ "zune-jpeg",
]
[[package]]
@@ -3084,10 +3104,12 @@ name = "printcraft-create"
version = "0.1.0"
dependencies = [
"hayro-syntax",
+ "image",
"png 0.18.1",
"printcraft-cos",
"printcraft-fonts",
"thiserror 2.0.21",
+ "tiff",
]
[[package]]
@@ -3119,6 +3141,7 @@ name = "printcraft-engine"
version = "0.1.0"
dependencies = [
"chrono",
+ "image",
"png 0.18.1",
"printcraft-annot",
"printcraft-cos",
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index 066799012..9a93c9b48 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -406,11 +406,18 @@ impl Automation {
let folder = self.resolve(a.str("folder")?, true)?;
std::fs::create_dir_all(&folder).map_err(|e| failed(format!("{}: {e}", folder.display())))?;
let dpi = a.opt_num("dpi")?.unwrap_or(150.0);
+ let quality = a.opt_int("quality")?.unwrap_or(85).clamp(1, 100) as u8;
+ let format = match a.opt_str("format")?.unwrap_or("png") {
+ "png" => printcraft_engine::export::ImageFormat::Png,
+ "jpeg" | "jpg" => printcraft_engine::export::ImageFormat::Jpeg { quality },
+ "tiff" | "tif" => printcraft_engine::export::ImageFormat::Tiff,
+ f => return Err(ToolError::InvalidArgs(format!("unknown format {f:?} (png, jpeg, tiff)"))),
+ };
let mut files = Vec::new();
for p in pages {
- let png = ex.png(p, dpi).map_err(failed)?;
- let path = folder.join(format!("{stem}_page_{}.png", p + 1));
- write_atomic(&path, &png)?;
+ let img = ex.image(p, dpi, format).map_err(failed)?;
+ let path = folder.join(format!("{stem}_page_{}.{}", p + 1, format.extension()));
+ write_atomic(&path, &img)?;
files.push(path.to_string_lossy().into_owned());
}
Ok(json!({ "count": files.len(), "files": files }))
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index cafc55baa..668bd0fad 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -483,9 +483,19 @@ pub fn tools() -> Vec<ToolDef> {
t("doc_remove_marks", "Remove header & footer, watermark or background", "Remove every header and footer, watermark or background PrintCraft (or a compatible tool) added. Undoable.")
.destructive()
.with(schema(json!({ "doc": doc(), "kind": { "type": "string", "enum": ["header_footer", "watermark", "background"] } }), &["doc", "kind"])),
- t("doc_export_images", "Export pages as images", "Write pages as PNG files (`<name>_page_<n>.png`) into a folder, at a resolution (default 150 dpi). Includes unsaved edits.")
+ t("doc_export_images", "Export pages as images", "Write pages as PNG, JPEG or TIFF files (`<name>_page_<n>.png|jpg|tif`) into a folder, at a resolution (default 150 dpi). JPEG and TIFF are flattened onto white paper. Includes unsaved edits.")
.cmd("export.image")
- .with(schema(json!({ "doc": doc(), "folder": { "type": "string" }, "dpi": { "type": "number", "minimum": 18, "maximum": 1200 }, "pages": pages("to export (default: all)") }), &["doc", "folder"])),
+ .with(schema(
+ json!({
+ "doc": doc(),
+ "folder": { "type": "string" },
+ "format": { "type": "string", "enum": ["png", "jpeg", "tiff"] },
+ "quality": { "type": "integer", "minimum": 1, "maximum": 100, "description": "JPEG quality (default 85)." },
+ "dpi": { "type": "number", "minimum": 18, "maximum": 1200 },
+ "pages": pages("to export (default: all)"),
+ }),
+ &["doc", "folder"],
+ )),
t("doc_export_text", "Export text", "Write the reading-order text of pages to a .txt file (pages separated by form feeds).")
.cmd("export.text")
.with(schema(json!({ "doc": doc(), "path": { "type": "string" }, "pages": pages("to export (default: all)") }), &["doc", "path"])),
@@ -509,7 +519,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"doc_create",
"Create a PDF",
- "Create a new, unsaved document and return it like doc_open: `blank` (pages, width, height in points; default 1 US Letter page), `images` (paths of PNG/JPEG files, one page each at the image's resolution) or `text` (a .txt path, or `text` directly). Save it with doc_save and a path.",
+ "Create a new, unsaved document and return it like doc_open: `blank` (pages, width, height in points; default 1 US Letter page), `images` (paths of PNG, JPEG, TIFF (every page), GIF or BMP files, one page each at the image's resolution) or `text` (a .txt path, or `text` directly). Save it with doc_save and a path.",
)
.with(schema(
json!({
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 4ca9e595d..204759fb9 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -528,6 +528,12 @@ fn exporting_images_and_text_through_tools() {
let r = ok(&mut a, "doc_export_images", json!({ "doc": doc, "folder": "out", "dpi": 72, "pages": [1, 3] }));
assert_eq!(r["count"], 2);
assert!(dir.join("out/a_page_3.png").exists());
+ ok(&mut a, "doc_export_images", json!({ "doc": doc, "folder": "out", "dpi": 72, "pages": [2], "format": "jpeg", "quality": 70 }));
+ assert!(std::fs::read(dir.join("out/a_page_2.jpg")).unwrap().starts_with(&[0xFF, 0xD8]));
+ ok(&mut a, "doc_export_images", json!({ "doc": doc, "folder": "out", "dpi": 72, "pages": [2], "format": "tiff" }));
+ let tif = std::fs::read(dir.join("out/a_page_2.tif")).unwrap();
+ assert!(tif.starts_with(b"II*\0") || tif.starts_with(b"MM\0*"));
+ assert!(matches!(a.call("doc_export_images", &json!({ "doc": doc, "folder": "out", "format": "webp" })), Err(ToolError::InvalidArgs(_))));
ok(&mut a, "doc_export_text", json!({ "doc": doc, "path": "a.txt" }));
assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "Page 1\n\u{c}Page 2\n\u{c}Page 3\n");
assert!(a.call("doc_export_text", &json!({ "doc": doc, "path": "/etc/x.txt" })).is_err(), "confined to the root");
diff --git a/crates/create/Cargo.toml b/crates/create/Cargo.toml
index 4b73c2706..19c88ac5a 100644
--- a/crates/create/Cargo.toml
+++ b/crates/create/Cargo.toml
@@ -12,7 +12,10 @@ workspace = true
printcraft-cos = { workspace = true }
printcraft-fonts = { workspace = true }
png = "0.18"
+tiff = "0.11"
+image = { version = "0.25", default-features = false, features = ["bmp", "gif"] }
thiserror = { workspace = true }
[dev-dependencies]
+image = { version = "0.25", default-features = false, features = ["bmp", "gif"] }
hayro-syntax = { workspace = true }
diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs
index 626ce345e..49ecd127e 100644
--- a/crates/create/src/lib.rs
+++ b/crates/create/src/lib.rs
@@ -184,14 +184,122 @@ fn png_image(name: &str, bytes: &[u8]) -> Result<Embedded, CreateError> {
Ok(Embedded { dict: d, data: colour, filtered: false, smask, px: (w, h), dpi })
}
-/// Detect the image format from its bytes.
-fn embed(name: &str, bytes: &[u8]) -> Result<Embedded, CreateError> {
+/// 8-bit RGBA pixels → an image (gray when every pixel is, with a soft mask when any pixel is
+/// not opaque).
+fn rgba_image(rgba: &[u8], (w, h): (u32, u32), dpi: (f64, f64)) -> Embedded {
+ let gray = rgba.chunks_exact(4).all(|p| p[0] == p[1] && p[1] == p[2]);
+ let opaque = rgba.chunks_exact(4).all(|p| p[3] == 255);
+ let colour: Vec<u8> =
+ if gray { rgba.chunks_exact(4).map(|p| p[0]).collect() } else { rgba.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect() };
+ let mut d = Dict::new();
+ d.set(b"ColorSpace".to_vec(), Object::name(if gray { "DeviceGray" } else { "DeviceRGB" }));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ let smask = (!opaque).then(|| {
+ let mut m = Dict::new();
+ m.set(b"Type".to_vec(), Object::name("XObject"));
+ m.set(b"Subtype".to_vec(), Object::name("Image"));
+ m.set(b"Width".to_vec(), Object::Int(w as i64));
+ m.set(b"Height".to_vec(), Object::Int(h as i64));
+ m.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
+ m.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ (m, rgba.chunks_exact(4).map(|p| p[3]).collect())
+ });
+ Embedded { dict: d, data: colour, filtered: false, smask, px: (w, h), dpi }
+}
+
+/// BMP and GIF (the first frame), through the `image` decoders. Their resolution is not read:
+/// 72 dpi, as for images without one.
+fn decoded(name: &str, bytes: &[u8], format: image::ImageFormat) -> Result<Embedded, CreateError> {
+ let img = image::load_from_memory_with_format(bytes, format).map_err(|e| CreateError::Image(name.into(), e.to_string()))?;
+ let rgba = img.to_rgba8();
+ Ok(rgba_image(rgba.as_raw(), rgba.dimensions(), (72.0, 72.0)))
+}
+
+/// Every page of a TIFF (multi-page scans become multi-page PDFs).
+fn tiff_pages(name: &str, bytes: &[u8]) -> Result<Vec<Embedded>, CreateError> {
+ use tiff::ColorType as C;
+ use tiff::decoder::{Decoder, DecodingResult};
+ use tiff::tags::Tag;
+ let bad = |m: String| CreateError::Image(name.into(), m);
+ let mut dec = Decoder::new(std::io::Cursor::new(bytes)).map_err(|e| bad(e.to_string()))?;
+ let mut out = Vec::new();
+ loop {
+ let (w, h) = dec.dimensions().map_err(|e| bad(e.to_string()))?;
+ let ct = dec.colortype().map_err(|e| bad(e.to_string()))?;
+ let unit = dec.get_tag_u32(Tag::ResolutionUnit).unwrap_or(2);
+ let res = |t: Tag, dec: &mut Decoder<std::io::Cursor<&[u8]>>| -> f64 {
+ // Resolutions are rationals.
+ let v = match dec.get_tag(t) {
+ Ok(tiff::decoder::ifd::Value::Rational(n, d)) if d != 0 => f64::from(n) / f64::from(d),
+ Ok(other) => other.into_f64().unwrap_or(72.0),
+ Err(_) => 72.0,
+ };
+ let v = if unit == 3 { v * 2.54 } else { v };
+ if v.is_finite() && v >= 1.0 { v } else { 72.0 }
+ };
+ let dpi = (res(Tag::XResolution, &mut dec), res(Tag::YResolution, &mut dec));
+ let data = match dec.read_image().map_err(|e| bad(e.to_string()))? {
+ DecodingResult::U8(v) => v,
+ // 16-bit samples: keep the high byte.
+ DecodingResult::U16(v) => v.iter().map(|x| (x >> 8) as u8).collect(),
+ _ => return Err(bad("this TIFF sample format isn't supported".into())),
+ };
+ let page = match ct {
+ C::Gray(1) => {
+ // Bilevel scans stay 1 bit per pixel (0 = black after the decoder's inversion).
+ let mut d = Dict::new();
+ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(1));
+ Embedded { dict: d, data, filtered: false, smask: None, px: (w, h), dpi }
+ }
+ C::Gray(8 | 16) => {
+ let mut d = Dict::new();
+ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ Embedded { dict: d, data, filtered: false, smask: None, px: (w, h), dpi }
+ }
+ C::RGB(8 | 16) => {
+ let mut d = Dict::new();
+ d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ Embedded { dict: d, data, filtered: false, smask: None, px: (w, h), dpi }
+ }
+ C::CMYK(8 | 16) => {
+ let mut d = Dict::new();
+ d.set(b"ColorSpace".to_vec(), Object::name("DeviceCMYK"));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ Embedded { dict: d, data, filtered: false, smask: None, px: (w, h), dpi }
+ }
+ C::RGBA(8 | 16) => rgba_image(&data, (w, h), dpi),
+ C::GrayA(8 | 16) => {
+ let rgba: Vec<u8> = data.chunks_exact(2).flat_map(|p| [p[0], p[0], p[0], p[1]]).collect();
+ rgba_image(&rgba, (w, h), dpi)
+ }
+ other => return Err(bad(format!("{other:?} TIFF images aren't supported yet"))),
+ };
+ out.push(page);
+ if !dec.more_images() {
+ break;
+ }
+ dec.next_image().map_err(|e| bad(e.to_string()))?;
+ }
+ Ok(out)
+}
+
+/// Detect the image format from its bytes; a TIFF may hold several pages.
+fn embed(name: &str, bytes: &[u8]) -> Result<Vec<Embedded>, CreateError> {
if bytes.starts_with(&[0xFF, 0xD8]) {
- jpeg(name, bytes)
+ Ok(vec![jpeg(name, bytes)?])
} else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
- png_image(name, bytes)
+ Ok(vec![png_image(name, bytes)?])
+ } else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
+ tiff_pages(name, bytes)
+ } else if bytes.starts_with(b"BM") {
+ Ok(vec![decoded(name, bytes, image::ImageFormat::Bmp)?])
+ } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
+ Ok(vec![decoded(name, bytes, image::ImageFormat::Gif)?])
} else {
- Err(CreateError::Image(name.into(), "only PNG and JPEG images are supported so far".into()))
+ Err(CreateError::Image(name.into(), "use a PNG, JPEG, TIFF, GIF or BMP image".into()))
}
}
@@ -201,8 +309,7 @@ pub fn from_images(images: &[(String, Vec<u8>)]) -> Result<Document, CreateError
return Err(CreateError::Invalid("no images".into()));
}
let mut doc = Document::new_empty();
- for (name, bytes) in images {
- let img = embed(name, bytes)?;
+ for img in images.iter().map(|(name, bytes)| embed(name, bytes)).collect::<Result<Vec<_>, _>>()?.into_iter().flatten() {
let (mut w, mut h) = (img.px.0 as f64 * 72.0 / img.dpi.0, img.px.1 as f64 * 72.0 / img.dpi.1);
// Keep huge images within the largest page PDF allows.
let k = (MAX_SIDE / w.max(h)).min(1.0);
diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rs
index cd7e095a7..4f0941424 100644
--- a/crates/create/src/tests.rs
+++ b/crates/create/src/tests.rs
@@ -97,3 +97,47 @@ fn text_is_wrapped_and_paginated() {
assert!(content(&p[0]).contains("(Line 0 of a plain text file) Tj"));
assert!(content(p.last().unwrap()).contains("(After a form feed) Tj"), "a form feed starts a page");
}
+
+fn image_of(doc: &Document, page: usize) -> Dict {
+ let p = &pages(doc)[page];
+ let res = doc.resolve(p.get(b"Resources").unwrap()).as_dict().cloned().unwrap();
+ let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();
+ match &*doc.resolve(xo.get(b"Im0").unwrap()) {
+ Object::Stream(s) => s.dict.clone(),
+ _ => panic!("not an image"),
+ }
+}
+
+#[test]
+fn bmp_gif_and_multi_page_tiff_images() {
+ use image::{ImageEncoder, Rgba, RgbaImage};
+ // BMP: 3×2 opaque colour.
+ let mut bmp = Vec::new();
+ image::codecs::bmp::BmpEncoder::new(&mut bmp).write_image(&[10, 20, 30].repeat(6), 3, 2, image::ExtendedColorType::Rgb8).unwrap();
+ // GIF: 2×2 with a transparent pixel.
+ let mut gif = Vec::new();
+ {
+ let mut img = RgbaImage::from_pixel(2, 2, Rgba([255, 0, 0, 255]));
+ img.put_pixel(0, 0, Rgba([0, 0, 0, 0]));
+ let mut enc = image::codecs::gif::GifEncoder::new(&mut gif);
+ enc.encode(img.as_raw(), 2, 2, image::ExtendedColorType::Rgba8).unwrap();
+ }
+ // TIFF: two pages, an 8-bit gray one at 144 dpi and a 1-bit one.
+ let mut tif = std::io::Cursor::new(Vec::new());
+ {
+ let mut enc = tiff::encoder::TiffEncoder::new(&mut tif).unwrap();
+ let mut im = enc.new_image::<tiff::encoder::colortype::Gray8>(4, 2).unwrap();
+ im.resolution(tiff::tags::ResolutionUnit::Inch, tiff::encoder::Rational { n: 144, d: 1 });
+ im.write_data(&[128; 8]).unwrap();
+ enc.write_image::<tiff::encoder::colortype::Gray8>(2, 2, &[0, 255, 255, 0]).unwrap();
+ }
+ let doc = from_images(&[("a.bmp".into(), bmp), ("b.gif".into(), gif), ("scan.tif".into(), tif.into_inner())]).unwrap();
+ let doc = reopen(&doc);
+ assert_eq!(pages(&doc).len(), 4, "one page per BMP and GIF, two for the TIFF");
+ assert_eq!(media(&pages(&doc)[0]), [0.0, 0.0, 3.0, 2.0]);
+ assert_eq!(image_of(&doc, 0).name(b"ColorSpace"), Some(&b"DeviceRGB"[..]));
+ assert!(image_of(&doc, 1).contains(b"SMask"), "GIF transparency");
+ assert_eq!(media(&pages(&doc)[2]), [0.0, 0.0, 2.0, 1.0], "4×2 px at 144 dpi");
+ assert_eq!(image_of(&doc, 2).name(b"ColorSpace"), Some(&b"DeviceGray"[..]));
+ assert!(matches!(from_images(&[("x.webp".into(), b"RIFF0000WEBP".to_vec())]), Err(CreateError::Image(..))));
+}
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 42c2a1778..7802445a7 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -9,6 +9,7 @@ license.workspace = true
workspace = true
[dependencies]
+image = { version = "0.25", default-features = false, features = ["jpeg", "tiff"] }
printcraft-render = { workspace = true }
printcraft-cos = { workspace = true }
printcraft-organize = { workspace = true }
diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs
index eba2cd1e8..b9de21a41 100644
--- a/crates/engine/src/export.rs
+++ b/crates/engine/src/export.rs
@@ -1,6 +1,7 @@
//! Export a PDF ▸ Image and Text (execution plan M10.3, the first formats).
//!
-//! [`Exporter`] renders pages to PNG at a resolution and extracts reading-order text, from a
+//! [`Exporter`] renders pages to PNG, JPEG or TIFF at a resolution and extracts reading-order
+//! text, from a
//! document's working file (so unsaved edits and hidden layers are respected, as on screen).
use printcraft_render::{PageRenderer, RenderRequest, RequestKind};
@@ -51,6 +52,20 @@ impl Exporter {
encode_png(r.width, r.height, &r.rgba)
}
+ /// Page `page` as an image file of `format`.
+ pub fn image(&mut self, page: usize, dpi: f64, format: ImageFormat) -> Result<Vec<u8>, String> {
+ self.check(page)?;
+ let r = self.renderer.render(RenderRequest { page, scale: (dpi.clamp(18.0, 1200.0) / 72.0) as f32, ..Default::default() });
+ if let Some(e) = r.error {
+ return Err(format!("page {}: {e}", page + 1));
+ }
+ match format {
+ ImageFormat::Png => encode_png(r.width, r.height, &r.rgba),
+ ImageFormat::Jpeg { quality } => encode_jpeg(r.width, r.height, &r.rgba, quality),
+ ImageFormat::Tiff => encode_tiff(r.width, r.height, &r.rgba),
+ }
+ }
+
/// The reading-order text of a page.
pub fn text(&mut self, page: usize) -> Result<String, String> {
self.check(page)?;
@@ -95,3 +110,63 @@ pub fn encode_png(width: u32, height: u32, premultiplied: &[u8]) -> Result<Vec<u
w.finish().map_err(|e| e.to_string())?;
Ok(out)
}
+
+/// Image file formats for Export ▸ Image.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ImageFormat {
+ Png,
+ /// Quality 1–100.
+ Jpeg {
+ quality: u8,
+ },
+ Tiff,
+}
+
+impl ImageFormat {
+ pub fn extension(self) -> &'static str {
+ match self {
+ ImageFormat::Png => "png",
+ ImageFormat::Jpeg { .. } => "jpg",
+ ImageFormat::Tiff => "tif",
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ ImageFormat::Png => "PNG",
+ ImageFormat::Jpeg { .. } => "JPEG",
+ ImageFormat::Tiff => "TIFF",
+ }
+ }
+}
+
+/// Premultiplied RGBA composited over white → RGB.
+fn over_white(premultiplied: &[u8]) -> Vec<u8> {
+ premultiplied
+ .chunks_exact(4)
+ .flat_map(|p| {
+ let k = 255 - p[3];
+ [p[0].saturating_add(k), p[1].saturating_add(k), p[2].saturating_add(k)]
+ })
+ .collect()
+}
+
+/// Premultiplied RGBA → baseline JPEG (pages are opaque: transparency becomes white paper).
+pub fn encode_jpeg(width: u32, height: u32, premultiplied: &[u8], quality: u8) -> Result<Vec<u8>, String> {
+ use image::ImageEncoder;
+ let rgb = over_white(premultiplied);
+ let mut out = Vec::new();
+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100))
+ .write_image(&rgb, width, height, image::ExtendedColorType::Rgb8)
+ .map_err(|e| e.to_string())?;
+ Ok(out)
+}
+
+/// Premultiplied RGBA → TIFF (RGB, LZW-compressed by the encoder's default).
+pub fn encode_tiff(width: u32, height: u32, premultiplied: &[u8]) -> Result<Vec<u8>, String> {
+ use image::ImageEncoder;
+ let rgb = over_white(premultiplied);
+ let mut out = std::io::Cursor::new(Vec::new());
+ image::codecs::tiff::TiffEncoder::new(&mut out).write_image(&rgb, width, height, image::ExtendedColorType::Rgb8).map_err(|e| e.to_string())?;
+ Ok(out.into_inner())
+}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 319c1998c..4fd3c9e5a 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -835,3 +835,20 @@ fn flattening_keeps_the_look_and_drops_the_objects() {
s.undo(id).unwrap();
assert_eq!(s.get(id).unwrap().form.len(), 2);
}
+
+#[test]
+fn pages_export_as_png_jpeg_and_tiff() {
+ use crate::export::{Exporter, ImageFormat};
+ let (s, id) = session_with(1);
+ let mut ex = Exporter::new(s.get(id).unwrap());
+ let png = ex.image(0, 72.0, ImageFormat::Png).unwrap();
+ assert!(png.starts_with(b"\x89PNG"));
+ let jpg = ex.image(0, 72.0, ImageFormat::Jpeg { quality: 85 }).unwrap();
+ let decoded = image::load_from_memory_with_format(&jpg, image::ImageFormat::Jpeg).unwrap();
+ assert_eq!((decoded.width(), decoded.height()), (200, 300), "the page at 72 dpi");
+ let corner = decoded.to_rgb8().get_pixel(2, 2).0;
+ assert!(corner.iter().all(|c| *c > 240), "white paper, not black: {corner:?}");
+ let tif = ex.image(0, 144.0, ImageFormat::Tiff).unwrap();
+ let decoded = image::load_from_memory_with_format(&tif, image::ImageFormat::Tiff).unwrap();
+ assert_eq!((decoded.width(), decoded.height()), (400, 600));
+}
diff --git a/crates/ui-egui/src/create_ui.rs b/crates/ui-egui/src/create_ui.rs
index f96632298..adea973e7 100644
--- a/crates/ui-egui/src/create_ui.rs
+++ b/crates/ui-egui/src/create_ui.rs
@@ -6,10 +6,16 @@ use std::sync::Arc;
use crate::PrintCraftApp;
/// File types Open accepts besides PDF (converted on open).
-pub const CONVERTIBLE: [&str; 4] = ["png", "jpg", "jpeg", "txt"];
+pub const CONVERTIBLE: [&str; 9] = ["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "txt", "text"];
fn is_image(bytes: &[u8]) -> bool {
- bytes.starts_with(&[0xFF, 0xD8]) || bytes.starts_with(b"\x89PNG\r\n\x1a\n")
+ bytes.starts_with(&[0xFF, 0xD8])
+ || bytes.starts_with(b"\x89PNG\r\n\x1a\n")
+ || bytes.starts_with(b"II*\0")
+ || bytes.starts_with(b"MM\0*")
+ || bytes.starts_with(b"GIF8")
+ // BMP: "BM" and a known header size (so text starting with "BM" stays text).
+ || (bytes.starts_with(b"BM") && bytes.get(14..18).is_some_and(|h| matches!(u32::from_le_bytes([h[0], h[1], h[2], h[3]]), 12 | 40 | 52 | 56 | 108 | 124)))
}
fn stem(name: &str) -> &str {
@@ -56,7 +62,11 @@ impl PrintCraftApp {
pub(crate) fn create_from_images_dialog(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
{
- let Some(files) = rfd::FileDialog::new().add_filter("Images", &["png", "jpg", "jpeg"]).set_title("Choose images").pick_files() else {
+ let Some(files) = rfd::FileDialog::new()
+ .add_filter("Images", &["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp"])
+ .set_title("Choose images")
+ .pick_files()
+ else {
return;
};
let mut images = Vec::new();
diff --git a/crates/ui-egui/src/export_ui.rs b/crates/ui-egui/src/export_ui.rs
index 21b605948..a0612ce86 100644
--- a/crates/ui-egui/src/export_ui.rs
+++ b/crates/ui-egui/src/export_ui.rs
@@ -1,4 +1,4 @@
-//! Export a PDF ▸ Image (PNG) and Text (Acrobat's Export a PDF tool, first formats).
+//! Export a PDF ▸ Image (PNG, JPEG, TIFF) and Text (Acrobat's Export a PDF tool, first formats).
//!
//! On the desktop the export runs on a worker thread and reports progress in the notice bar;
//! on the web it runs in place and downloads the files.
@@ -6,7 +6,7 @@
use std::sync::{Arc, Mutex};
use egui::{Align, Layout};
-use printcraft_engine::export::{ExportSource, Exporter};
+use printcraft_engine::export::{ExportSource, Exporter, ImageFormat};
use crate::marks_ui::PageRange;
use crate::theme::{self, Tokens};
@@ -22,11 +22,12 @@ pub enum ExportKind {
pub struct ExportDraft {
pub dpi: f64,
pub range: PageRange,
+ pub format: ImageFormat,
}
impl Default for ExportDraft {
fn default() -> Self {
- Self { dpi: 150.0, range: PageRange::default() }
+ Self { dpi: 150.0, range: PageRange::default(), format: ImageFormat::Png }
}
}
@@ -38,7 +39,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PrintCraftApp, t: &Tokens, kind:
let d = &mut app.export_draft;
ui.label(
egui::RichText::new(match kind {
- ExportKind::Image => "Export to Image (PNG)",
+ ExportKind::Image => "Export to Image",
ExportKind::Text => "Export to Text",
})
.font(theme::semibold(18.0)),
@@ -53,7 +54,28 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PrintCraftApp, t: &Tokens, kind:
}
});
});
- ui.label(egui::RichText::new("One PNG file per page, named after the document.").small().color(t.text_faint));
+ ui.horizontal(|ui| {
+ ui.label("Format");
+ let mut quality = match d.format {
+ ImageFormat::Jpeg { quality } => quality,
+ _ => 85,
+ };
+ egui::ComboBox::from_id_salt("export-format").selected_text(d.format.label()).show_ui(ui, |ui| {
+ for f in [ImageFormat::Png, ImageFormat::Jpeg { quality }, ImageFormat::Tiff] {
+ let on = std::mem::discriminant(&d.format) == std::mem::discriminant(&f);
+ if ui.selectable_label(on, f.label()).clicked() {
+ d.format = f;
+ }
+ }
+ });
+ if let ImageFormat::Jpeg { .. } = d.format {
+ ui.label("Quality");
+ if ui.add(egui::Slider::new(&mut quality, 10..=100)).changed() {
+ d.format = ImageFormat::Jpeg { quality };
+ }
+ }
+ });
+ ui.label(egui::RichText::new(format!("One {} file per page, named after the document.", d.format.label())).small().color(t.text_faint));
} else {
ui.label(egui::RichText::new("Plain text in reading order; pages are separated by form feeds.").small().color(t.text_faint));
}
@@ -75,10 +97,12 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PrintCraftApp, t: &Tokens, kind:
}
/// Write the files (`name`, bytes) produced for `pages`, reporting progress.
+#[allow(clippy::too_many_arguments)]
fn run(
src: ExportSource,
kind: ExportKind,
dpi: f64,
+ format: ImageFormat,
pages: Vec<usize>,
stem: String,
mut sink: impl FnMut(&str, Vec<u8>) -> Result<(), String>,
@@ -95,7 +119,7 @@ fn run(
ExportKind::Image => {
for (k, p) in pages.iter().enumerate() {
set(k, None);
- let result = ex.png(*p, dpi).and_then(|png| sink(&format!("{stem}_page_{}.png", p + 1), png));
+ let result = ex.image(*p, dpi, format).and_then(|img| sink(&format!("{stem}_page_{}.{}", p + 1, format.extension()), img));
if let Err(e) = result {
return format!("Export stopped: {e}");
}
@@ -121,6 +145,7 @@ impl PrintCraftApp {
let stem = doc.name.trim_end_matches(".pdf").trim_end_matches(".PDF").to_string();
let pages = self.export_draft.range.pages(src.pages);
let dpi = self.export_draft.dpi;
+ let format = self.export_draft.format;
let status: ExportStatus = Arc::new(Mutex::new(Some((0, pages.len(), None))));
#[cfg(not(target_arch = "wasm32"))]
{
@@ -135,7 +160,7 @@ impl PrintCraftApp {
let sink = |name: &str, bytes: Vec<u8>| {
crate::editing::write_atomically(&dir.join(name).to_string_lossy(), &bytes).map_err(|e| format!("{name}: {e}"))
};
- let msg = run(src, kind, dpi, pages, stem, sink, &st);
+ let msg = run(src, kind, dpi, format, pages, stem, sink, &st);
if let Ok(mut s) = st.lock() {
let (done, total) = s.as_ref().map_or((0, 0), |(d, t, _)| (*d, *t));
*s = Some((done.max(total), total, Some(format!("{msg} to {shown}"))));
@@ -149,7 +174,7 @@ impl PrintCraftApp {
}
#[cfg(target_arch = "wasm32")]
{
- let msg = run(src, kind, dpi, pages, stem, |name, bytes| crate::editing::download(name, &bytes), &status);
+ let msg = run(src, kind, dpi, format, pages, stem, |name, bytes| crate::editing::download(name, &bytes), &status);
if let Ok(mut s) = status.lock() {
*s = Some((0, 0, Some(msg)));
}
diff --git a/crates/ui-egui/tests/export.rs b/crates/ui-egui/tests/export.rs
index 63a7004cd..4e05c7ec3 100644
--- a/crates/ui-egui/tests/export.rs
+++ b/crates/ui-egui/tests/export.rs
@@ -27,7 +27,7 @@ fn export_dialogs_write_images_and_text() {
h.run_steps(4);
assert!(h.state_mut().execute("export.image"));
h.run_steps(2);
- h.get_by_label("Export to Image (PNG)");
+ h.get_by_label("Export to Image");
h.get_by_label("Export").click();
h.run_steps(4);
assert!(dir.join("doc_page_1.png").exists() && dir.join("doc_page_2.png").exists());
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 4387f7db8..6fe8a87ff 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -6646,8 +6646,8 @@ milestone = "M10"
status = "partial"
commands = ["create.images", "create.file"]
tools = ["doc_create"]
-evidence = ["crates/ui-egui/tests/create.rs::opening_images_and_text_converts_them_to_new_pdfs", "crates/create/src/tests.rs::images_become_pages_at_their_resolution"]
-notes = "PNG and JPEG (grey, RGB, CMYK; transparency kept); TIFF, GIF, BMP, JPEG 2000 not yet"
+evidence = ["crates/ui-egui/tests/create.rs::opening_images_and_text_converts_them_to_new_pdfs", "crates/create/src/tests.rs::images_become_pages_at_their_resolution", "crates/create/src/tests.rs::bmp_gif_and_multi_page_tiff_images"]
+notes = "PNG, JPEG, TIFF, GIF (first frame), BMP; JPEG 2000 pending"
[[feature]]
id = "create.from-multipage-tiff"
@@ -6655,11 +6655,11 @@ title = "Multi-page TIFF to multi-page PDF"
area = "J"
tier = "P0"
milestone = "M10"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "shipped"
+commands = ["create.images", "create.file"]
+tools = ["doc_create"]
+evidence = ["crates/create/src/tests.rs::bmp_gif_and_multi_page_tiff_images"]
+notes = "every page; 1-bit scans stay 1-bit; resolution from the TIFF"
[[feature]]
id = "create.from-text"
@@ -6883,11 +6883,11 @@ title = "Export pages as JPEG or TIFF"
area = "J"
tier = "P0"
milestone = "M10"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+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"
[[feature]]
id = "create.export-jpeg2000"