Optimization · Ruby
Compress a PDF in Ruby
Shrink PDF file size from Ruby. rust-pdf drops unreferenced objects, Flate-compresses uncompressed streams, dedupes byte-identical objects, and can pack everything into object streams with a cross-reference stream.
Last updated: 2026-06-29
Why Ruby needs this
Prawn has no notion of an existing file, so trimming a bloated PDF in Ruby has traditionally meant a Ghostscript or qpdf subprocess on the box. rust-pdf rewrites the file structure directly from the gem.
Optimization here is lossless structural cleanup: the rendered page never changes, the file carries less weight. Pair optimize (drop unused objects, Flate-compress streams, dedupe byte-identical ones) with compact (object and cross-reference streams) for the smallest valid output.
Run it from an ActiveJob or Sidekiq worker before you email or archive at scale: load_file, chain optimize.compact(true), then save, rescuing RustPdf::Error on a corrupt input. It all runs in-process over Fiddle, with no Ghostscript binary to ship.
- Drop unreferenced objects, Flate-compress streams and dedupe identical objects.
- Pack objects into object streams and emit a cross-reference stream for the smallest size.
- Lossless: the rendered page is unchanged, the output still passes qpdf and mutool.
Compress a PDF in Ruby with rust-pdf
Install with RubyGems, then call the same idiomatic API every rust-pdf binding shares. The snippet below is real Ruby code from the reference docs.
gem install rustpdf
ed = RustPdf::EditableDoc.load_file("big.pdf")
ed.optimize.compact(true)
ed.save("small.pdf")
ed.close
This is part of the free tier in Ruby. No license required.
Full Ruby reference in the documentation.
Compression in Ruby: FAQ
How much smaller will my PDF be in Ruby?
It depends on the input. Files with uncompressed streams, duplicated objects or no object streams shrink the most. Optimization is lossless, so the savings come from structure, not from degrading content.
Does compression reduce quality?
No. This is structural optimization, not image down-sampling. The rendered page is identical; only redundant or uncompressed structure is removed, so the output still validates.
Is optimization free?
Yes. Optimize and compact are part of the free tier in Ruby. No license is needed.
Can I optimize PDFs in a background worker?
Yes. Call load_file then optimize.compact(true) from an ActiveJob or Sidekiq worker before you archive or email at scale. It runs in-process over Fiddle with no Ghostscript subprocess, and a corrupt input is a RustPdf::Error you can rescue.
Ship leaner PDFs from your Ruby services
One Rust core, the same output across every language. Prototype for free, license the corporate features when you ship.