-
-
Save ismarsantos/ed07579eb5ce0a377a69c6b0889cce02 to your computer and use it in GitHub Desktop.
Generate and save a pdf to S3 with wicked_pdf and paperclip
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
# Main reference was lascarides' post at http://stackoverflow.com/questions/14743447/getting-pdf-from-wickedpdf-for-attachment-via-carrierwave | |
# estimate.rb | |
# ... | |
has_attached_file :pdf, | |
storage: :s3, | |
s3_credentials: { | |
access_key_id: ENV['AWS_ACCESS_KEY_ID'], | |
secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], | |
bucket: ENV['AWS_BUCKET'] | |
}, | |
s3_permissions: :private, | |
path: "/estimates/:id/:version/:filename" | |
Paperclip.interpolates :document_type do |attachment, style| | |
attachment.instance.document_type | |
end | |
Paperclip.interpolates :version do |attachment, style| | |
attachment.instance.latest_pdf_version | |
end | |
# ... | |
def generate_pdf | |
increment!(:latest_pdf_version) | |
pdf_string = WickedPdf.new.pdf_from_string( | |
ActionController::Base.new().render_to_string( | |
:template => '/finance/estimate', | |
:locals => { | |
:@estimate => self, | |
:@billing_client => billing_client, | |
:@shipping_client => shipping_client, | |
:@project => project | |
}, | |
:layout => false, | |
), | |
:pdf => estimate_number, | |
:layout => false, | |
:page_size => 'Letter', | |
:lowquality => false, | |
:handlers => [:erb], | |
:formats => [:html], | |
:margin => {:top => 5, | |
:bottom => 0, | |
:left => 0, | |
:right => 0}, | |
:orientation => 'Portrait', | |
:disposition => 'attachment' | |
) | |
tempfile = Tempfile.new(["#{estimate_number}", ".pdf"], Rails.root.join('tmp')) | |
tempfile.binmode | |
tempfile.write pdf_string | |
tempfile.close | |
self.pdf = File.open tempfile.path | |
self.pdf_file_name = "#{estimate_number}.pdf" | |
# Store secure url on the model, valid for 90 days | |
self.pdf_url = self.pdf.s3_object.url_for(:read, secure: true, expires: 90.days).to_s | |
save | |
tempfile.unlink | |
# Only keep 5 most recent versions | |
if self.latest_pdf_version > 5 | |
s3 = AWS::S3.new access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'] | |
s3.buckets[ENV['AWS_BUCKET']].objects["estimates/#{self.id}/#{self.latest_pdf_version - 5}/#{self.estimate_number}.pdf"].delete | |
s3.buckets[ENV['AWS_BUCKET']].objects["estimates/#{self.id}/#{self.latest_pdf_version - 5}"].delete | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment