Rails: How to print model's details to A4 PDF page?

一曲冷凌霜 提交于 2019-12-11 05:05:58

问题


In my Job Management application I would like to prepare an A4 page receipt to customer.

Thus, I need to print somehow Job model's details to a single A4 PDF page.

Are the any built-in tools in Rails for this purpose ?

If no, what would be the best way to go ?


回答1:


Basically there is two options: (any PDF creation requires a gem - no default PDF creation for rails).

  1. Create a pure PDF using Prawn, You have to do all the formatting using the Prawn API

  2. Create a HTML version of your receipt and convert it to PDF, One of the better gems to do this is PDFkit. which uses a web-kit powered browser engine.

They both work good, For one page documents I usually use PDFkit to convert HTML and for larger documents that are going have lots of pages I use Prawn because it gives you a smaller file size and handles multiple pages better.

My suggestion would be to make a HTML receipt and display it on the screen and give the user an option to save a PDF version using PDFkit.

EDIT: windows install. (not tested - windows and I have parted company.)

Download the windows installer for wkhtmltopdf: win-wkhtmltopdf

now create an initializer file, e.g. config/intializers/pdfkit_config.rb

in pdfkit_config.rb set the absolute path to wkhtmltopdf on your local machine:

PDFKit.configure do |config|
  if RAILS_ENV == 'development'
    config.wkhtmltopdf = 'D:\path\to\your\wkhtmltopdf' #this bit i'm not sure about
  else
    config.wkhtmltopdf = "#{RAILS_ROOT}/lib/wkhtmltopdf"
  end
end

for your production ENV you can actually just have a copy of wkhtmltopdf in you repo, a unix version of course. (remember to chmod +x it before you git add it)




回答2:


Theres a gem called prawn that helps with PDF generation. Here is a tutorial using it for some ideas:

http://railstips.org/blog/archives/2008/10/13/how-to-generate-pdfs-in-rails-with-prawn/



来源:https://stackoverflow.com/questions/5163315/rails-how-to-print-models-details-to-a4-pdf-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!