PDF Compress — Rust source
Shrink PDF file sizes in your browser — lossless optimization plus a JPEG quality slider for embedded images. Nothing uploads.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! pdf-compress — the lossless floor for Rust with lopdf (crates.io).
//! Honest scope note: the Rust ecosystem has no mature pure-Rust re-encoder
//! for embedded JPEGs (the TS canvas path has no clean client-side analogue
//! here), so the closest idiomatic equivalent is pass 1 — metadata strip
//! plus a re-save — with the ChooseImageAction decision ported verbatim so
//! the JPEG walk can be added the moment a decoder crate earns its keep.
//! (Driving `qpdf --object-streams=generate` via std::process::Command is
//! the practical production alternative; see the leading comment.)
use std::fmt;
/// Load failure kind: Encrypted (password-protected) or Invalid (unparseable).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
Encrypted,
Invalid,
}
/// The Rust twin of the TS PdfToolError class.
#[derive(Debug)]
pub struct PdfToolError {
pub kind: ErrorKind,
pub message: String,
}
impl fmt::Display for PdfToolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for PdfToolError {}
/// Pure classifier — encrypted vs invalid, from the raw error message.
fn classify_load_error(msg: &str) -> ErrorKind {
let lower = msg.to_ascii_lowercase();
if lower.contains("encrypt") || lower.contains("password") {
ErrorKind::Encrypted
} else {
ErrorKind::Invalid
}
}
fn map_error(e: lopdf::Error) -> PdfToolError {
match e {
lopdf::Error::InvalidPassword => PdfToolError {
kind: ErrorKind::Encrypted,
message: "This PDF is password-protected. Unlock it first.".into(),
},
other => {
let kind = classify_load_error(&other.to_string());
let message = if kind == ErrorKind::Encrypted {
"This PDF is password-protected. Unlock it first.".into()
} else {
"Not a readable PDF file.".into()
};
PdfToolError { kind, message }
}
}
}
/// Per-image outcome: before/after stream sizes, or why the original stayed.
pub struct ImageAccounting {
pub index: usize,
pub before: usize,
pub after: Option<usize>,
pub skipped: Option<&'static str>, // "grew" | "not-jpeg" | "decode-failed"
}
/// Pure decision: only baseline single-stream JPEGs (/Filter /DCTDecode) are
/// recompressible — anything else stays byte-for-byte intact. Ported
/// verbatim from chooseImageAction() in src/lib/pdf-compress.ts.
pub fn choose_image_action(filter: &str) -> &'static str {
if filter == "DCTDecode" {
"recompress"
} else {
"skip"
}
}
/// Lossless metadata strip — clears the Info dict entries the TS pass-1
/// floor blanks via setTitle('')/setAuthor('')/... .
fn strip_metadata(doc: &mut lopdf::Document) {
if let Some(info_id) = doc.trailer.get(b"Info").ok().and_then(|o| o.as_reference().ok()) {
let empty = lopdf::Object::String("".into(), lopdf::StringFormat::Literal);
if let Ok(dict) = doc.get_object_mut(info_id).and_then(|o| o.as_dict_mut()) {
for name in ["Title", "Author", "Subject", "Keywords", "Creator", "Producer"] {
dict.insert(name.as_bytes().to_vec(), empty.clone());
}
}
}
}
/// CompressPdf runs the pass-1 lossless floor: load (refusing encrypted
/// inputs), strip metadata, re-save. `quality < 1` would enable the JPEG
/// walk; the re-encode step itself needs a rasterizer (see scope note), so
/// the floor is what this snippet ships.
pub fn compress_pdf(bytes: &[u8], quality: f64) -> Result<(Vec<u8>, Vec<ImageAccounting>), PdfToolError> {
let mut doc = lopdf::Document::load_mem(bytes).map_err(map_error)?;
strip_metadata(&mut doc);
let images = Vec::new(); // pass 2 (JPEG walk) not wired: no pure-Rust re-encoder
let _ = quality;
let mut out = Vec::new();
doc.save_to(&mut out).map_err(map_error)?;
Ok((out, images))
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →