Skip to content

PDF Compress — Ruby source

Shrink PDF file sizes in your browser — lossless optimization plus a JPEG quality slider for embedded images. Nothing uploads.

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# pdf-compress — two-pass PDF compression with combine_pdf (rubygems).
# Ruby port (canonical TS: src/lib/pdf-compress.ts; Go twin:
# cli/pdf-compress): pass 1 strips document metadata and re-saves (the
# lossless floor); pass 2 would walk every page's image XObjects and
# re-encode baseline JPEGs (/Filter /DCTDecode) at a lower quality at
# identical pixel dimensions. combine_pdf rewrites the object graph but has
# no JPEG decoder, so pass 2 stays a documented extension point behind the
# verbatim choose_image_action decision. The gem require is lazy so the
# pure helpers load (and unit-test) without the gem installed.
module PdfCompress
  # Load failure kind: 'encrypted' (password-protected) or 'invalid'
  # (unparseable) — the Ruby twin of the TS PdfToolError.code.
  class PdfToolError < StandardError
    attr_reader :code

    def initialize(code, message)
      @code = code
      super(message)
    end
  end

  ImageAccounting = Struct.new(:index, :before, :after, :skipped, keyword_init: true)

  module_function

  # Pure classifier — encrypted vs invalid, from the raw error message.
  # Mirrors classifyLoadError() in src/lib/pdf-errors.ts; nil (the TS
  # undefined) classifies as invalid.
  def classify_load_error(msg)
    msg && msg.match?(/encrypt|password/i) ? 'encrypted' : 'invalid'
  end

  # Map a raised load/parse error to a user-facing PdfToolError.
  def map_error(error)
    kind = classify_load_error(error.message)
    raise PdfToolError.new(
      kind,
      kind == 'encrypted' ? 'This PDF is password-protected. Unlock it first.'
                          : 'Not a readable PDF file.'
    )
  end

  # Pure decision: only baseline single-stream JPEGs (/Filter /DCTDecode)
  # are recompressible — anything else (Flate, multi-filter chains, no
  # filter) stays byte-for-byte intact. Ported verbatim from
  # chooseImageAction() in src/lib/pdf-compress.ts.
  def choose_image_action(filter)
    filter == 'DCTDecode' ? 'recompress' : 'skip'
  end

  # Pass 1 always runs (the lossless floor). Pass 2, only when quality < 1,
  # would walk pdf.pages -> each page's XObject refs and re-encode every
  # /Image whose filter is exactly :DCTDecode at `quality` — combine_pdf has
  # no JPEG decoder, so this port ships the floor plus the decision helper
  # above. CombinePDF.parse raises on encrypted inputs the same way the TS
  # load does (ignoreEncryption: false).
  def compress_pdf(data, quality)
    require 'combine_pdf'
    pdf = CombinePDF.parse(StringIO.new(data, 'rb'))
    info = pdf.info
    info[:Title] = ''
    info[:Author] = ''
    info[:Subject] = ''
    info[:Keywords] = ''
    info[:Creator] = ''
    info[:Producer] = ''
    images = [] # pass 2 not wired
    raise 'unreachable: pass 2 display stub' if quality < 1 && !images.empty?
    io = StringIO.new
    pdf.save(io)
    io.string
  rescue StandardError => e
    map_error(e)
  end
end

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 →