All formats

CombinePDF

LanguageRuby
LicenseMIT
Repositorygithub.com/boazsegev/combine_pdf
DocumentationREADME
Depends onruby-rc4, matrix (gems)
Read / writeyes / yes: merge, split, rotate, stamp pages, page numbers, simple text boxes, metadata; no text extraction

CombinePDF parses PDF files into Ruby objects and writes them back. It merges files, takes pages out of documents, rotates pages, overlays one page on another (watermarks, letterheads, Prawn-generated content) and numbers pages. It’s pure Ruby and fast enough for web apps that assemble documents on the fly.

It doesn’t extract text, render pages or fill forms, and it reads only some encrypted files (no password support) and can’t write encrypted ones. Some complex or broken PDFs fail to parse; HexaPDF or qpdf handle them better.

Installation#

Shell
gem install combine_pdf

Basic usage: merge PDF files#

Ruby
require "combine_pdf"

pdf = CombinePDF.new
pdf << CombinePDF.load("a.pdf")
pdf << CombinePDF.load("b.pdf")
pdf.save "merged.pdf"

CombinePDF.parse(data) parses a PDF from a string, and pdf.to_pdf returns the result as a string (for send_data in Rails).

How to split a PDF and extract pages#

Ruby
src = CombinePDF.load("in.pdf")
src.pages.each_with_index do |page, i|
  single = CombinePDF.new
  single << page
  single.save "page-#{i + 1}.pdf"
end

first_two = CombinePDF.new
src.pages[0..1].each { |page| first_two << page }
first_two.save "first-two.pdf"

How to rotate pages#

Ruby
pdf = CombinePDF.load("in.pdf")
pdf.pages.each { |page| page.rotate_right }  # also rotate_left, rotate_180
pdf.save "rotated.pdf"

How to add a watermark or stamp#

Overlay the first page of another PDF (for example one generated with Prawn) on every page:

Ruby
stamp = CombinePDF.load("stamp.pdf").pages[0]
pdf = CombinePDF.load("in.pdf")
pdf.pages.each { |page| page << stamp }  # use page >> stamp to put it underneath
pdf.save "stamped.pdf"

How to add page numbers#

Ruby
pdf = CombinePDF.load("in.pdf")
pdf.number_pages(number_format: " %s ", location: [:bottom], font_size: 10)
pdf.save "numbered.pdf"

page.textbox "Draft", x: 10, y: 10, width: 100, height: 20, font_size: 10 writes simple text on a page.

How to read and change metadata#

Ruby
pdf = CombinePDF.load("in.pdf")
puts pdf.version
puts pdf.info[:Title], pdf.info[:Author]
pdf.info[:Title] = "New title"
pdf.save "out.pdf"

Tips#