Aparichith
Aparichith

Reputation: 1537

How to use pdfkit to render image in rails app?

Can anyone step-by-step or with example explain how to install and use pdfkit in rails to render images present in html.?

I have installed pdfkit along with wkhtmltopdf-binary. When i do

require 'pdfkit'
kit = PDFKit.new('http://google.com')
gpdf = kit.to_file('/home/blackat/Desktop/gpdf.pdf')

it will generate a pdf of google home page perfectly. So it is meant that pdfkit installed correctly in my system(correct me if it is wrong).

As mentioned in the railcast i did all the changes.

  1. gem 'pdfkit' # in my Gemfile

  2. bundle install

  3. require 'pdfkit' # in application.rb
  4. config.middleware.use "PDFKit::Middleware", :print_media_type => true #in application.rb

to check weather it works or not i did some workaround in my controller like this

html_data = render_to_string :layout => false
html_file_path = "demo.html"
pdf_file_path = "demo.pdf"
f = File.open(html_file_path, "w")
f.write(html_data)
f.close

kit = PDFKit.new(html_data,:page_size => 'Letter')
pdf_file = kit.to_file(pdf_file_path)

When i remove images from my html.erb template, a pdf will generate. If i specify any images in my erb template or if i include ".pdf" in browser execution hangs for lifetime.

Where i am doing wrong? is there any blog/example to refer?

Does the 'wkhtmltopdf' installed correctly?

Please help me in this. i am trying this from 2 weeks.

I am using rails '3.2.11' and ruby 1.9.3

Thanks in advance.

Upvotes: 0

Views: 2995

Answers (1)

Anuja Joshi
Anuja Joshi

Reputation: 718

Try giving absolute path of image file in your view like:

%img{src: "file://#{Rails.root}/public/imagesmyImage.png"}

Upvotes: 1

Related Questions