[pdf] Compress: E-mail (≤ 5 MB), Web and Print presets; images downsampled and re-encoded, text untouched
This commit is contained in:
@@ -0,0 +1,236 @@
|
|||||||
|
//! Compress presets (Day 2): images are downsampled to the preset's resolution and re-encoded as JPEG, every stream
|
||||||
|
//! is Flate-compressed, unreferenced objects are dropped and the file is written with object streams. Text, fonts,
|
||||||
|
//! vector content and the page structure are not touched, so all text stays extractable.
|
||||||
|
//!
|
||||||
|
//! "Resolution" needs no content-stream analysis: an image is never shown larger than the largest page, so its
|
||||||
|
//! pixel size is capped at (largest page side in inches × the preset's dpi). Images Pictor cannot decode safely
|
||||||
|
//! (JPEG 2000, CCITT, JBIG2, indexed or 16-bit colour, masks) are left as they are. Fonts are not subset (a gap,
|
||||||
|
//! recorded in docs/02_v1-1.md of the app).
|
||||||
|
use crate::{PdfError, lopdf_load};
|
||||||
|
use image::{DynamicImage, GenericImageView};
|
||||||
|
use lopdf::{Dictionary, Document, Object, Stream};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum CompressPreset {
|
||||||
|
/// Small enough to attach to an e-mail: target 5 MB or less.
|
||||||
|
Email,
|
||||||
|
/// For the web and the screen.
|
||||||
|
Web,
|
||||||
|
/// Good enough to print.
|
||||||
|
Print,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The E-mail preset's target.
|
||||||
|
pub const EMAIL_TARGET: usize = 5 << 20;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Compressed {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub before: usize,
|
||||||
|
pub after: usize,
|
||||||
|
pub images_changed: usize,
|
||||||
|
/// Plain sentences (for example: the E-mail target could not be reached).
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Step {
|
||||||
|
dpi: f32,
|
||||||
|
quality: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn steps(preset: CompressPreset) -> &'static [Step] {
|
||||||
|
match preset {
|
||||||
|
CompressPreset::Email => &[Step { dpi: 120.0, quality: 62 }, Step { dpi: 96.0, quality: 55 }, Step { dpi: 72.0, quality: 50 }],
|
||||||
|
CompressPreset::Web => &[Step { dpi: 150.0, quality: 72 }],
|
||||||
|
CompressPreset::Print => &[Step { dpi: 300.0, quality: 86 }],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compresses a document with a preset. A protected document stays protected with the same password.
|
||||||
|
pub fn compress(bytes: &[u8], password: Option<&str>, preset: CompressPreset) -> Result<Compressed, PdfError> {
|
||||||
|
let mut last = None;
|
||||||
|
for (i, step) in steps(preset).iter().enumerate() {
|
||||||
|
let r = compress_step(bytes, password, step)?;
|
||||||
|
let done = preset != CompressPreset::Email || r.after <= EMAIL_TARGET || i + 1 == steps(preset).len();
|
||||||
|
last = Some(r);
|
||||||
|
if done {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut r = last.expect("at least one step");
|
||||||
|
if preset == CompressPreset::Email && r.after > EMAIL_TARGET {
|
||||||
|
r.warnings.push(format!(
|
||||||
|
"Pictor got it down to {:.1} MB; the rest is text, fonts and drawings it does not change.",
|
||||||
|
r.after as f64 / 1048576.0
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Never hand back something bigger than the original.
|
||||||
|
if r.after >= r.before {
|
||||||
|
r.bytes = bytes.to_vec();
|
||||||
|
r.after = r.before;
|
||||||
|
r.images_changed = 0;
|
||||||
|
r.warnings.push("This PDF is already as small as Pictor can make it.".into());
|
||||||
|
}
|
||||||
|
Ok(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compress_step(bytes: &[u8], password: Option<&str>, step: &Step) -> Result<Compressed, PdfError> {
|
||||||
|
let mut doc = lopdf_load(bytes, password)?;
|
||||||
|
let largest_side_in = largest_page_side(&doc) / 72.0;
|
||||||
|
let max_px = (largest_side_in * step.dpi).ceil().max(64.0) as u32;
|
||||||
|
let ids: Vec<_> = doc.objects.keys().copied().collect();
|
||||||
|
let masks = soft_masks(&doc);
|
||||||
|
let mut changed = 0;
|
||||||
|
for id in ids {
|
||||||
|
if masks.contains(&id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(Object::Stream(s)) = doc.objects.get(&id) else { continue };
|
||||||
|
if !is_image(&s.dict) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(new) = recompress(&doc, s, max_px, step.quality) else { continue };
|
||||||
|
if let Some(Object::Stream(s)) = doc.objects.get_mut(&id) {
|
||||||
|
*s = new;
|
||||||
|
changed += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
doc.compress();
|
||||||
|
doc.prune_objects();
|
||||||
|
let opts = lopdf::SaveOptions::builder().use_object_streams(true).use_xref_streams(true).build();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
match password {
|
||||||
|
Some(p) => {
|
||||||
|
let plain = {
|
||||||
|
let mut v = Vec::new();
|
||||||
|
doc.save_with_options(&mut v, opts).map_err(|e| PdfError::Write(e.to_string()))?;
|
||||||
|
v
|
||||||
|
};
|
||||||
|
out = crate::protect(&plain, None, p, None)?;
|
||||||
|
}
|
||||||
|
None => doc.save_with_options(&mut out, opts).map_err(|e| PdfError::Write(e.to_string()))?,
|
||||||
|
}
|
||||||
|
Ok(Compressed { before: bytes.len(), after: out.len(), bytes: out, images_changed: changed, warnings: Vec::new() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn largest_page_side(doc: &Document) -> f32 {
|
||||||
|
let mut side: f32 = 0.0;
|
||||||
|
for page in doc.get_pages().values() {
|
||||||
|
let f = crate::edit::lopdf_frame(doc, *page);
|
||||||
|
side = side.max(f.crop[2] - f.crop[0]).max(f.crop[3] - f.crop[1]);
|
||||||
|
}
|
||||||
|
if side <= 0.0 { 842.0 } else { side.min(14_400.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Images used as another image's soft mask: left alone (their size must stay what their parent expects).
|
||||||
|
fn soft_masks(doc: &Document) -> std::collections::HashSet<lopdf::ObjectId> {
|
||||||
|
doc.objects
|
||||||
|
.values()
|
||||||
|
.filter_map(|o| match o {
|
||||||
|
Object::Stream(s) => s.dict.get(b"SMask").ok().and_then(|m| m.as_reference().ok()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_image(d: &Dictionary) -> bool {
|
||||||
|
matches!(d.get(b"Subtype"), Ok(Object::Name(n)) if n == b"Image")
|
||||||
|
&& !matches!(d.get(b"ImageMask"), Ok(Object::Boolean(true)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name_or_first(o: Option<&Object>) -> Option<Vec<u8>> {
|
||||||
|
match o? {
|
||||||
|
Object::Name(n) => Some(n.clone()),
|
||||||
|
Object::Array(a) if a.len() == 1 => a[0].as_name().ok().map(|n| n.to_vec()),
|
||||||
|
Object::Array(a) if a.is_empty() => Some(Vec::new()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Channels of a colour space Pictor can re-encode as JPEG: DeviceGray, DeviceRGB, or ICCBased with N 1 or 3.
|
||||||
|
fn channels(doc: &Document, cs: Option<&Object>) -> Option<u8> {
|
||||||
|
let cs = match cs? {
|
||||||
|
Object::Reference(r) => doc.get_object(*r).ok()?,
|
||||||
|
o => o,
|
||||||
|
};
|
||||||
|
match cs {
|
||||||
|
Object::Name(n) if n == b"DeviceGray" => Some(1),
|
||||||
|
Object::Name(n) if n == b"DeviceRGB" => Some(3),
|
||||||
|
Object::Array(a) if a.len() == 2 && a[0].as_name().ok() == Some(b"ICCBased") => {
|
||||||
|
let s = match &a[1] {
|
||||||
|
Object::Reference(r) => doc.get_object(*r).ok()?.as_stream().ok()?,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
match s.dict.get(b"N").ok()?.as_i64().ok()? {
|
||||||
|
1 => Some(1),
|
||||||
|
3 => Some(3),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recompress(doc: &Document, s: &Stream, max_px: u32, quality: u8) -> Option<Stream> {
|
||||||
|
let d = &s.dict;
|
||||||
|
let w = d.get(b"Width").ok()?.as_i64().ok()? as u32;
|
||||||
|
let h = d.get(b"Height").ok()?.as_i64().ok()? as u32;
|
||||||
|
if w == 0 || h == 0 || (w as u64) * (h as u64) > 150_000_000 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if d.get(b"BitsPerComponent").ok().and_then(|b| b.as_i64().ok()) != Some(8) || d.has(b"Decode") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n = channels(doc, d.get(b"ColorSpace").ok())?;
|
||||||
|
let filter = name_or_first(d.get(b"Filter").ok()).unwrap_or_default();
|
||||||
|
let img: DynamicImage = match &filter[..] {
|
||||||
|
b"DCTDecode" => {
|
||||||
|
let i = image::load_from_memory_with_format(&s.content, image::ImageFormat::Jpeg).ok()?;
|
||||||
|
// CMYK JPEGs (Adobe) and odd channel counts are left alone.
|
||||||
|
if i.color().channel_count() != n {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
i
|
||||||
|
}
|
||||||
|
b"FlateDecode" | b"" => {
|
||||||
|
let raw = if filter.is_empty() { s.content.clone() } else { s.decompressed_content_with_limit(600 << 20).ok()? };
|
||||||
|
let need = (w as usize) * (h as usize) * n as usize;
|
||||||
|
if raw.len() < need {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match n {
|
||||||
|
1 => DynamicImage::ImageLuma8(image::GrayImage::from_raw(w, h, raw[..need].to_vec())?),
|
||||||
|
_ => DynamicImage::ImageRgb8(image::RgbImage::from_raw(w, h, raw[..need].to_vec())?),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
let (iw, ih) = img.dimensions();
|
||||||
|
let img = if iw.max(ih) > max_px + max_px / 10 {
|
||||||
|
let k = max_px as f32 / iw.max(ih) as f32;
|
||||||
|
img.resize_exact(((iw as f32 * k).round() as u32).max(1), ((ih as f32 * k).round() as u32).max(1), image::imageops::FilterType::Lanczos3)
|
||||||
|
} else {
|
||||||
|
img
|
||||||
|
};
|
||||||
|
let mut jpeg = Vec::new();
|
||||||
|
let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, quality);
|
||||||
|
match n {
|
||||||
|
1 => img.to_luma8().write_with_encoder(enc).ok()?,
|
||||||
|
_ => img.to_rgb8().write_with_encoder(enc).ok()?,
|
||||||
|
}
|
||||||
|
let old = s.content.len();
|
||||||
|
if jpeg.len() as f64 > old as f64 * 0.9 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut dict = d.clone();
|
||||||
|
dict.set("Width", img.width() as i64);
|
||||||
|
dict.set("Height", img.height() as i64);
|
||||||
|
dict.set("Filter", "DCTDecode");
|
||||||
|
dict.remove(b"DecodeParms");
|
||||||
|
dict.remove(b"Length");
|
||||||
|
let mut out = Stream::new(dict, jpeg);
|
||||||
|
out.allows_compression = false;
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
//! Every function takes the document as bytes plus an optional password and returns new bytes: nothing here touches
|
//! Every function takes the document as bytes plus an optional password and returns new bytes: nothing here touches
|
||||||
//! the file system. Outside files are hostile; call these only inside `pictor-worker`.
|
//! the file system. Outside files are hostile; call these only inside `pictor-worker`.
|
||||||
|
|
||||||
|
mod compress;
|
||||||
mod edit;
|
mod edit;
|
||||||
mod engine;
|
mod engine;
|
||||||
mod error;
|
mod error;
|
||||||
@@ -17,6 +18,7 @@ mod reader;
|
|||||||
mod redact;
|
mod redact;
|
||||||
mod security;
|
mod security;
|
||||||
|
|
||||||
|
pub use compress::{CompressPreset, Compressed, EMAIL_TARGET, compress};
|
||||||
pub use edit::*;
|
pub use edit::*;
|
||||||
pub use engine::Engine;
|
pub use engine::Engine;
|
||||||
pub use error::PdfError;
|
pub use error::PdfError;
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//! Day 2 mandatory test 5: compress presets. The output is smaller, opens in pdfium, keeps every page and keeps all
|
||||||
|
//! text extractable; the E-mail preset reaches its 5 MB target for a heavy scan-like PDF.
|
||||||
|
mod common;
|
||||||
|
use common::*;
|
||||||
|
use lopdf::{Document, Object, Stream, dictionary};
|
||||||
|
use pictor_pdf::CompressPreset;
|
||||||
|
|
||||||
|
/// `pages` A4 pages, each with a line of text and a noisy `px` × `px` photo (Flate RGB, or JPEG at q95).
|
||||||
|
fn heavy_pdf(pages: usize, px: u32, jpeg: bool) -> Vec<u8> {
|
||||||
|
let mut doc = Document::with_version("1.7");
|
||||||
|
let pages_id = doc.new_object_id();
|
||||||
|
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
|
||||||
|
let mut kids = Vec::new();
|
||||||
|
let mut seed = 0x1234_5678u32;
|
||||||
|
for p in 0..pages {
|
||||||
|
let img = image::RgbImage::from_fn(px, px, |x, y| {
|
||||||
|
seed ^= seed << 13;
|
||||||
|
seed ^= seed >> 17;
|
||||||
|
seed ^= seed << 5;
|
||||||
|
let n = (seed & 0x1f) as u8;
|
||||||
|
image::Rgb([(x * 255 / px) as u8 ^ n, (y * 255 / px) as u8, 120u8.wrapping_add(n)])
|
||||||
|
});
|
||||||
|
let stream = if jpeg {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95).encode_image(&img).unwrap();
|
||||||
|
let mut s = Stream::new(
|
||||||
|
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => px as i64, "Height" => px as i64,
|
||||||
|
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Filter" => "DCTDecode"},
|
||||||
|
out,
|
||||||
|
);
|
||||||
|
s.allows_compression = false;
|
||||||
|
s
|
||||||
|
} else {
|
||||||
|
let mut s = Stream::new(
|
||||||
|
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => px as i64, "Height" => px as i64,
|
||||||
|
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8},
|
||||||
|
img.into_raw(),
|
||||||
|
);
|
||||||
|
s.compress().unwrap();
|
||||||
|
s
|
||||||
|
};
|
||||||
|
let im = doc.add_object(stream);
|
||||||
|
let content = format!("BT /F1 18 Tf 72 780 Td (Invoice page {} of the compress test) Tj ET q 450 0 0 450 72 250 cm /Im0 Do Q", p + 1);
|
||||||
|
let c = doc.add_object(Stream::new(dictionary! {}, content.into_bytes()));
|
||||||
|
let page = doc.add_object(dictionary! {
|
||||||
|
"Type" => "Page", "Parent" => pages_id, "Contents" => c,
|
||||||
|
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}, "XObject" => dictionary! {"Im0" => im}},
|
||||||
|
});
|
||||||
|
kids.push(Object::Reference(page));
|
||||||
|
}
|
||||||
|
doc.objects.insert(
|
||||||
|
pages_id,
|
||||||
|
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => pages as i64,
|
||||||
|
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||||
|
);
|
||||||
|
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||||
|
doc.trailer.set("Root", cat);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
doc.save_to(&mut out).unwrap();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn texts(bytes: &[u8]) -> Vec<String> {
|
||||||
|
pictor_pdf::extract_text(engine(), bytes, None).unwrap().into_iter().map(|t| t.trim().to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_preset_makes_it_smaller_and_keeps_the_text() {
|
||||||
|
let input = heavy_pdf(3, 2400, false);
|
||||||
|
let before = texts(&input);
|
||||||
|
for preset in [CompressPreset::Email, CompressPreset::Web, CompressPreset::Print] {
|
||||||
|
let out = pictor_pdf::compress(&input, None, preset).unwrap();
|
||||||
|
assert!(out.bytes.len() < input.len(), "{preset:?} did not shrink ({} → {})", input.len(), out.bytes.len());
|
||||||
|
assert_eq!(out.before, input.len());
|
||||||
|
assert_eq!(out.after, out.bytes.len());
|
||||||
|
assert_eq!(texts(&out.bytes), before, "{preset:?} lost text");
|
||||||
|
let sizes = pictor_pdf::page_sizes(engine(), &out.bytes, None).unwrap();
|
||||||
|
assert_eq!(sizes.len(), 3);
|
||||||
|
assert!(out.images_changed >= 3, "{preset:?}: {} images changed", out.images_changed);
|
||||||
|
// It still renders: the photo is there (not white) in the middle of the page.
|
||||||
|
let img = pictor_pdf::render_page(engine(), &out.bytes, None, 0, 595).unwrap().to_rgb8();
|
||||||
|
let p = img.get_pixel(297, 400).0;
|
||||||
|
assert!(p != [255, 255, 255], "{preset:?}: the photo disappeared");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn presets_are_ordered_email_smallest_print_largest() {
|
||||||
|
let input = heavy_pdf(2, 2400, true);
|
||||||
|
let email = pictor_pdf::compress(&input, None, CompressPreset::Email).unwrap().after;
|
||||||
|
let web = pictor_pdf::compress(&input, None, CompressPreset::Web).unwrap().after;
|
||||||
|
let print = pictor_pdf::compress(&input, None, CompressPreset::Print).unwrap().after;
|
||||||
|
assert!(email <= web && web <= print, "email {email}, web {web}, print {print}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn email_reaches_five_megabytes() {
|
||||||
|
let input = heavy_pdf(8, 3000, false);
|
||||||
|
assert!(input.len() > 20 << 20, "fixture too small: {}", input.len());
|
||||||
|
let out = pictor_pdf::compress(&input, None, CompressPreset::Email).unwrap();
|
||||||
|
assert!(out.after <= 5 << 20, "E-mail preset left {} bytes", out.after);
|
||||||
|
assert_eq!(texts(&out.bytes).len(), 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_pdf_with_nothing_to_shrink_is_left_alone_and_says_so() {
|
||||||
|
let input = numbered_pdf(2, "Plain");
|
||||||
|
let out = pictor_pdf::compress(&input, None, CompressPreset::Web).unwrap();
|
||||||
|
assert_eq!(out.images_changed, 0);
|
||||||
|
assert!(out.after <= out.before + 64, "grew from {} to {}", out.before, out.after);
|
||||||
|
assert_eq!(texts(&out.bytes), ["Plain page 1", "Plain page 2"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_protected_pdf_needs_its_password_and_stays_readable() {
|
||||||
|
let locked = pictor_pdf::protect(&heavy_pdf(1, 1600, false), None, "pw", None).unwrap();
|
||||||
|
assert!(pictor_pdf::compress(&locked, None, CompressPreset::Web).is_err());
|
||||||
|
let out = pictor_pdf::compress(&locked, Some("pw"), CompressPreset::Web).unwrap();
|
||||||
|
assert!(out.after < out.before);
|
||||||
|
// Still protected, with the same password.
|
||||||
|
assert!(pictor_pdf::is_encrypted(&out.bytes));
|
||||||
|
let text = pictor_pdf::extract_text(engine(), &out.bytes, Some("pw")).unwrap();
|
||||||
|
assert_eq!(text[0].trim(), "Invoice page 1 of the compress test");
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user