class CombinePDF::PDF

PDF class is the PDF object that can save itself to a file and that can be used as a container for a full PDF file data, including version, information etc’.

PDF objects can be used to combine or to inject data.

Combine/Merge PDF files or Pages

To combine PDF files (or data):

pdf = CombinePDF.new
pdf << CombinePDF.load("file1.pdf") # one way to combine, very fast.
pdf << CombinePDF.load("file2.pdf")
pdf.save "combined.pdf"

or even a one liner:

(CombinePDF.load("file1.pdf") << CombinePDF.load("file2.pdf") << CombinePDF.load("file3.pdf")).save("combined.pdf")

you can also add just odd or even pages:

pdf = CombinePDF.new
i = 0
CombinePDF.load("file.pdf").pages.each do |page|
  i += 1
  pdf << page if i.even?
end
pdf.save "even_pages.pdf"

notice that adding all the pages one by one is slower then adding the whole file.

Add content to existing pages (Stamp / Watermark)

To add content to existing PDF pages, first import the new content from an existing PDF file. after that, add the content to each of the pages in your existing PDF.

in this example, we will add a company logo to each page:

company_logo = CombinePDF.load("company_logo.pdf").pages[0]
pdf = CombinePDF.load "content_file.pdf"
pdf.pages.each {|page| page << company_logo} # notice the << operator is on a page and not a PDF object.
pdf.save "content_with_logo.pdf"

Notice the << operator is on a page and not a PDF object. The << operator acts differently on PDF objects and on Pages.

The << operator defaults to secure injection by renaming references to avoid conflics. For overlaying pages using compressed data that might not be editable (due to limited filter support), you can use:

pdf.pages(nil, false).each {|page| page << stamp_page}

Page Numbering

adding page numbers to a PDF object or file is as simple as can be:

pdf = CombinePDF.load "file_to_number.pdf"
pdf.number_pages
pdf.save "file_with_numbering.pdf"

numbering can be done with many different options, with different formating, with or without a box object, and even with opacity values.

Loading PDF data

Loading PDF data can be done from file system or directly from the memory.

Loading data from a file is easy:

pdf = CombinePDF.load("file.pdf")

you can also parse PDF files from memory:

pdf_data = IO.read 'file.pdf' # for this demo, load a file to memory
pdf = CombinePDF.parse(pdf_data)

Loading from the memory is especially effective for importing PDF data recieved through the internet or from a different authoring library such as Prawn.