Skip to content

PDF Split — Ruby source

Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.

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

# frozen_string_literal: true

# pdf-split — split one PDF into many by page plan with combine_pdf
# (rubygems combine_pdf). Authored snippet mirroring src/lib/pdf-split.ts:
# the planner (parse_page_ranges + plan_names) is a pure port of the TS
# grammar — 'all', 'N/chunk', or comma-separated 'a-b' ranges and single
# pages (1-based, inclusive) — and split_pdf writes one PDF per planned
# group with the same naming rules.

require 'combine_pdf'

# Load failure kind: 'encrypted' (password-protected) or 'invalid' (unparseable).
class PdfToolError < StandardError
  attr_reader :code

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

# Split output: the planned file name, its bytes, and its page count.
SplitOutput = Struct.new(:name, :bytes, :page_count)

# Pure classifier — encrypted vs invalid, from the raw error message.
def classify_load_error(msg)
  return 'invalid' unless msg
  return 'encrypted' if msg.match?(/encrypt|password/i)

  'invalid'
end

# Map a raised load failure to a user-facing PdfToolError.
def map_error(error)
  if classify_load_error(error.message) == 'encrypted'
    PdfToolError.new('encrypted', 'This PDF is password-protected. Unlock it first.')
  else
    PdfToolError.new('invalid', 'Not a readable PDF file.')
  end
end

# The 1-based pages [a..b], inclusive.
def page_range(a, b)
  (a..b).to_a
end

# Pure planner — no combine_pdf on this path. Grammar (mirrors
# parsePageRanges in src/lib/pdf-split.ts):
#   'all'       -> [[1], [2], ..., [page_count]]
#   'N/chunk'   -> groups of N pages in order (last group may be short)
#   'a-b,c-d,e' -> [[a..b], [c..d], [e]] (1-based, inclusive)
#
# Raises PdfToolError('invalid') on empty specs, unparseable tokens,
# descending ranges, and any page outside 1..page_count.
def parse_page_ranges(spec, page_count)
  trimmed = spec.strip
  raise PdfToolError.new('invalid', 'Enter a page range first.') if trimmed.empty?

  if trimmed == 'all'
    return (1..page_count).map { |p| [p] }
  end

  if (chunk = trimmed.match(/\A(\d+)\/chunk\z/))
    size = chunk[1].to_i
    if size < 1 || size > page_count
      raise PdfToolError.new('invalid', "Chunk size must be between 1 and #{page_count}.")
    end
    groups = []
    start = 1
    while start <= page_count
      groups << page_range(start, [start + size - 1, page_count].min)
      start += size
    end
    return groups
  end

  trimmed.split(',').map do |token|
    t = token.strip
    if (single = t.match(/\A(\d+)\z/))
      page = single[1].to_i
      if page < 1 || page > page_count
        raise PdfToolError.new('invalid', "Page #{page} is out of range (1–#{page_count}).")
      end
      [page]
    elsif (span = t.match(/\A(\d+)-(\d+)\z/))
      a = span[1].to_i
      b = span[2].to_i
      if b < a
        raise PdfToolError.new('invalid', "Range #{a}-#{b} descends — use a-b with a ≤ b.")
      end
      if a < 1 || b > page_count
        raise PdfToolError.new('invalid', "Range #{a}-#{b} is out of range (1–#{page_count}).")
      end
      page_range(a, b)
    else
      raise PdfToolError.new('invalid', "\"#{t}\" is not a page, a-b range, \"all\", or \"N/chunk\".")
    end
  end
end

# Chunk-shaped = partition of 1..n into equal runs of >=2 pages (last may be
# short). Size-1 "chunks" are indistinguishable from 'all' — those stay
# page-N.
def chunk_shaped(groups)
  return false if groups.length < 2

  size = groups.first.length
  return false if size < 2

  next_page = 1
  groups.each_with_index do |group, i|
    return false if group.first != next_page

    next_page = group.last + 1
    return false if i < groups.length - 1 && group.length != size
    return false if i == groups.length - 1 && group.length > size
  end
  true
end

# Pure naming pass: single page -> 'page-N.pdf'; chunk-shaped plan ->
# 'chunk-K.pdf'; contiguous group -> 'pages-A-B.pdf'; else 'pages-A,B.pdf'.
def plan_names(groups)
  chunk = chunk_shaped(groups)
  groups.each_with_index.map do |group, i|
    if chunk
      "chunk-#{i + 1}.pdf"
    elsif group.length == 1
      "page-#{group.first}.pdf"
    elsif group.last - group.first + 1 == group.length
      "pages-#{group.first}-#{group.last}.pdf"
    else
      "pages-#{group.join(',')}.pdf"
    end
  end
end

# One output PDF per group: the source is parsed once, then each planned page
# is appended into a fresh CombinePDF document (the combine_pdf analogue of
# pdf-lib's copyPages). Mirrors splitPdf() in src/lib/pdf-split.ts.
def split_pdf(data, groups)
  raise PdfToolError.new('invalid', 'Nothing to split — plan at least one page.') if groups.empty?

  src = CombinePDF.parse(data)
  total = src.pages.length
  names = plan_names(groups)
  groups.each_with_index.map do |group, i|
    group.each do |page|
      if page < 1 || page > total
        raise PdfToolError.new('invalid', "Page #{page} is out of range (1–#{total}).")
      end
    end
    out = CombinePDF.new
    group.each { |page| out << src.pages[page - 1] }
    SplitOutput.new(names[i], out.to_pdf, out.pages.length)
  end
rescue StandardError => e
  raise e if e.is_a?(PdfToolError)

  raise map_error(e)
end

# Page count for UI display — the Ruby twin of the TS countPages() helper.
def count_pages(data)
  reader = CombinePDF.parse(data)
  reader.pages.length
rescue StandardError => e
  raise e if e.is_a?(PdfToolError)

  raise map_error(e)
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 →