0
votes

I'm using Prawn gem to generate PDFs In my application...

app/controllers/orders.rb

class OrdersController < ApplicationController
  ...
  def show
    respond_to do |format|
      format.html
      format.pdf do
        require "prawn/measurement_extensions"
        ...
        #render pdf document
        send_data pdf.render, 
          filename: "order_#{@order.id}.pdf", 
          type: 'application/pdf',
          disposition: 'inline'
      end
    end
  end
  ...
end

And It's working fine for displaying, But My questions are..

  • How to -Automatically- save those generated pdfs in the public folder (folder for each day) after a successful order creation? I've tried searching Prawn Documentation But I've found nothing.
  • How to show orders in only pdf format? I've Tried to Comment the format.html line but It didn't work
2
Storing things in the public folder on a particular server isn't something you want to do if you a) ever want to run more than one server or b) run on heroku. You'd want to use a file storage system like S3 where all your servers can access the files and the files persist between reboots. If you don't care about that, just use the ruby File methods to write pdf.render (the contents) to disk. If you do care about persisting across server changes, check out something github.com/thoughtbot/paperclip where you can persist files and associate them with models in your application - John Naegle
@JohnNaegle The thing I want to do now is to save a PDF Invoice after order creation, to be able to view it later. Can you advise me what is the best way to achieve that? - Moataz Zaitoun

2 Answers

0
votes

When you call pdf.render and send it to the client with send_data, you're actually dumping the contents of the pdf over the wire. Instead of that, you could dump the result of pdf.render in a file with File.new and use send_file in the controller. Check the documentation for File. Alternatively, you could attach the generated pdf to the specific order using something like Paperclip.

If you generate the pdf as a file in the server, you should use send_file instead of send_data. Read more about this in the guides.

0
votes

You can use Prawn's render_file method to save the generated PDF to a file:

pdf.render_file(Rails.root.join('public', "order_#{@order.id}.pdf"))

See documentation: https://prawnpdf.org/docs/0.11.1/Prawn/Document.html