Skip to content

Instantly share code, notes, and snippets.

@adamico
Created July 30, 2015 12:46
Show Gist options
  • Save adamico/4148ad0f9a3377e06bff to your computer and use it in GitHub Desktop.
Save adamico/4148ad0f9a3377e06bff to your computer and use it in GitHub Desktop.
Use CombinePDF in a Rails app to merge existing PDF files with Prawn generated PDF content
# app/pdfs/appel_pdf.rb
class AppelPdf < Prawn::Document
def initialize(appel)
text 'Content for Appel PDF'
end
end
# app/models/document.rb
class Document < ActiveRecord::Base
belongs_to :foobar
has_attached_file :attachment
validates_attachment :attachment,
content_type: { content_type: ['image/jpeg', 'image/gif', 'image/png', 'application/pdf']
end
# app/models/foobar.rb
class Foobar < ActiveRecord::Base
has_many :documents
def pdf_documents
documents.where('attachment_content_type LIKE ?', '%pdf%').map do |pdf_document|
File.new(pdf_document.attachment.path)
end
end
end
class FoobarsController < ApplicationController
def show
@foobar = Foobar.find(params[:id])
respond_to do |format|
format.pdf do
foobar_pdf = FoobarPdf.new(@foobar).render
final_pdf = CombinePDF.new
final_pdf << CombinePDF.parse(foobar_pdf)
if @foobar.pdf_documents.any?
@foobar.pdf_documents.each do |pdf_document|
final_pdf << CombinePDF.parse(IO.read(pdf_document))
end
end
send_data final_pdf.to_pdf, filename: "foobar_#{@foobar.id}", type: 'application/pdf', disposition: 'inline'
end
end
end
end
gem 'combine_pdf'
gem 'prawn'
gem 'paperclip'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment