Skip to content

PDF Merge — Ruby source

Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.

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

# frozen_string_literal: true

# pdf-merge — merge many PDFs into one with combine_pdf (rubygems).
#
# Language: Ruby (3.1+), the combine_pdf gem for the PDF I/O (display-only
# dependency — the pure helpers below run standalone, so the require is
# guarded).
# CosmoDev polyglot showcase port of the `pdf-merge` tool.
# Ported from src/lib/pdf-merge.ts — display source, part of CosmoDev's
# polyglot tool pages.
#
# Same contract: empty input rejected, encrypted vs invalid classified from
# the raw parse-error message, page count returned for UI display. Every
# page of every input is appended, in order, into one fresh CombinePDF
# document.

begin
  require 'combine_pdf'
rescue LoadError
  # Display-only dependency — drivers exercise the pure helpers below.
end

# The Ruby twin of the TS PdfToolError class. code is 'encrypted'
# (password-protected) or 'invalid' (unparseable).
class PdfToolError < StandardError
  attr_reader :code

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

ENCRYPTED_MESSAGE = 'This PDF is password-protected. Unlock it first.'
INVALID_MESSAGE = 'Not a readable PDF file.'

# Pure classifier — encrypted vs invalid, from the raw error message.
def classify_load_error(msg)
  return 'invalid' if msg.nil?

  msg.match?(/encrypt|password/i) ? 'encrypted' : 'invalid'
end

# Map a raised parse error to a user-facing PdfToolError.
def map_error(err)
  kind = classify_load_error(err.message)
  PdfToolError.new(kind, kind == 'encrypted' ? ENCRYPTED_MESSAGE : INVALID_MESSAGE)
end

MergeResult = Struct.new(:bytes, :page_count)

# Copy every page of every input, in order, into one fresh document —
# the Ruby twin of mergePdfs() in src/lib/pdf-merge.ts.
def merge_pdfs(docs)
  raise PdfToolError.new('invalid', 'Nothing to merge.') if docs.empty?
  raise LoadError, 'the combine_pdf gem is required for PDF I/O' unless defined?(CombinePDF)

  out = CombinePDF.new
  begin
    docs.each do |bytes|
      src = CombinePDF.parse(bytes)
      # combine_pdf refuses to decrypt; a locked parse surfaces here as the
      # TS ignoreEncryption: false path
      raise PdfToolError.new('encrypted', ENCRYPTED_MESSAGE) if src.pages.empty? && encrypted?(bytes)

      out << src
    end
  rescue PdfToolError
    raise
  rescue StandardError => e
    raise map_error(e)
  end
  MergeResult.new(out.to_pdf, out.pages.length)
end

# Page count for UI display — the tool's only other combine_pdf need.
def count_pages(bytes)
  src = CombinePDF.parse(bytes)
  raise PdfToolError.new('encrypted', ENCRYPTED_MESSAGE) if src.pages.empty? && encrypted?(bytes)

  src.pages.length
rescue PdfToolError
  raise
rescue StandardError => e
  raise map_error(e)
end

# combine_pdf parses encrypted files but serves no pages; a raw %ENCRYPT
# marker in the trailer is the display-only heuristic this twin shows.
def encrypted?(bytes)
  bytes.is_a?(String) && bytes.include?('/Encrypt')
end

if __FILE__ == $PROGRAM_NAME
  # classifyLoadError — the src/lib/pdf-merge.test.ts vectors.
  classify_cases = [
    ['Input document to PDFDocument.load is encrypted', 'encrypted'],
    ['wrong password for this document', 'password'],
    ['Failed to parse PDF', 'parse'],
    [nil, 'null'],
  ]
  classify_cases.each do |(msg, label)|
    puts format('%s-msg -> %s', label, classify_load_error(msg) == 'encrypted' ? 'encrypted' : 'invalid')
  end

  # empty input throws invalid
  begin
    merge_pdfs([])
  rescue PdfToolError => e
    puts "empty-input -> #{e.code}: #{e.message}"
  end

  # mapError — encrypted classification propagates, message per kind
  enc = map_error(StandardError.new('Input document to PDFDocument.load is encrypted'))
  puts "map-encrypted -> #{enc.code}: #{enc.message}"
  inv = map_error(StandardError.new('Failed to parse PDF'))
  puts "map-invalid -> #{inv.code}: #{inv.message}"
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 →