128 lines
5.9 KiB
Rust
128 lines
5.9 KiB
Rust
//! 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");
|
||
}
|