Rails 3 + PDFKit: How to convert a view to PDF?

2020-03-30 16:02发布

问题:

In my Rails 3 application on Windows I have the following page which shows a job receipt and lets user to edit it:

http://localhost:3001/jobs/45/invoice

I have also a "Create PDF" button in the bottom of the page. When pressed, create_pdf_invoice of my JobsController is called:

def create_pdf_invoice
    job = Job.find(params[:id])

    kit = PDFKit.new("<h1>Hello</h1><p>This is PDF!!!</p>", :page_size => "A4")
    file = kit.to_file("my_file_name.pdf")

    redirect_to(:action => 'index')
  end
end

All this works fine, i.e. the PDF is created!

My question is how can I print the invoice itself rather than this static text (like if I press "Print" on the http://localhost:3001/jobs/45/invoice page) ?


UPDATE

I tried to put

require 'pdfkit'

and

config.middleware.use PDFKit::Middleware

in config/application.rb as suggested here.

The server starts normally, but when I go to

http://localhost:3001/jobs/45/invoice.pdf

Ruby crashes:

I use:

ruby 1.9.2p0 (2010-08-18) [i386-mingw32]
Rails 3.0.1
rake, version 0.8.7
pdfkit (0.5.0)

Any ideas ?

回答1:

first you need to tell the application to use pdfkit as a middleware.

So somewhere in an initializer you need to put:

# PDFKit
require 'pdfkit'
middleware.use PDFKit::Middleware

PDFKit.configure do |config|
  config.wkhtmltopdf = 'windows_path_to_wkhtmltopdf'
end

After this if you call

http://localhost:3001/jobs/45/invoice.pdf

a pdf should be generated for you.

PDFkit is a middleware that intercepts the pdf format rendering the page accordingly.

If you want you can also restrict pdfable routes in the config through regexes or string.

Just a caveat, if you have images in the page they must be called with an absolute path.

We are also finding some problems with pdfkit 0.5.0 but things are working fine with version 0.4.6 it is something to do with paths so maybe it can solve your issues.



回答2:

With the help of PDFKit middle-ware you can only view the html page in pdf format in the browser. If want to show the download prompt then you have to set the header in your action.

headers["Content-Disposition"] = "attachment; filename=export"

Further, If you want to save the pdf file in server then you can try this link.

Save PDF file shown by PDFKit middleware