Created
July 30, 2015 12:46
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/pdfs/appel_pdf.rb | |
class AppelPdf < Prawn::Document | |
def initialize(appel) | |
text 'Content for Appel PDF' | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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