Save PDF File Shown by Pdfkit Middleware

PDFKit: send the generated pdf to browser but don't save it

According to the PDFKit documentation there is a way to get an inline pdf like so:

kit = PDFKit.new(html, page_size: 'A4')
pdf = kit.to_pdf

You can send this pdf to the browser with send_data in your Controller.

send_data(pdf,
filename: 'some_fancy_file_name.pdf',
disposition: 'attachment',
type: :pdf)

Put this together in an action in your Controller and there you go. (Don’t forget to add an appropriate route!)

def download_pdf
html = # render as needed
kit = PDFKit.new(html, page_size: 'A4')
pdf = kit.to_pdf

send_data(pdf,
filename: 'some_fancy_file_name.pdf',
disposition: 'attachment',
type: :pdf)
end

How to create pdf file with layout applied to it. Using pdfkit gem

Without seeing your render_to_string method we can't tell what's going wrong. Here is example code for generating a pdf with layout: https://github.com/pdfkit/pdfkit#usage

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

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.

generating pdf hangs on rails 4 using PDFkit gem

The issue was due to stylesheet_link_tag and javascript_include_tag using relative URLs, which often causes wkhtmltopdf to hang when loading assets from the same server that wkhtmltopdf is running on.

Using absolute URLs for assets solved the problem.

Set asset_host in Rails' config, which also affects stylesheet_link_tag and javascript_include_tag:

# Modify asset host config setting in `config/application.rb`
# Or create a new initializer: `config/initializers/wkhtmltopdf.rb`
config.action_controller.asset_host = "http://mysite.com"

# Or you can have different hosts for development (local) and production (CDN):
# In `config/environments/development.rb`
config.action_controller.asset_host = "http://localhost"
# In `config/environments/production.rb`
config.action_controller.asset_host = "http://d111111abcdef8.cloudfront.net"

Trying to use PDFKit but dont know where to initialize

Non-Rails Rack apps

in config.ru

require 'pdfkit' 
use PDFKit::Middleware

From the documentation

I'm assuming you're using a config.ru setup



Related Topics



Leave a reply



Submit