How to use pdfkit to render image in rails app? - ruby-on-rails

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.
gem 'pdfkit' # in my Gemfile
bundle install
require 'pdfkit' # in application.rb
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.

Try giving absolute path of image file in your view like:
%img{src: "file://#{Rails.root}/public/imagesmyImage.png"}

Related

Trying to use PDFKit but dont know where to initialize

After running into difficulty with Prawn I have decided to use PDFKit. In doing so I followed the following link:
Rails 3 + PDFKit: How to convert a view to PDF?
The problem is that my ruby on rails application is quite unusual in that it doesnt seem to follow the usual structure. In the link it says to place the following in the initializer:
require 'pdfkit'
middleware.use PDFKit::Middleware
PDFKit.configure do |config|
config.wkhtmltopdf = 'windows_path_to_wkhtmltopdf'
end
Where would i place this? I have an app.rb file which i tried to place this in but got the following error:
undefined method `use' for [[Sass::Plugin::Rack, [], nil]]:Array
The stacktrace points to the line:
middleware.use PDFKit::Middleware
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
I have an application that uses WickedPDF, and there I only need to place
gem 'wkhtmltopdf-binary'
gem 'wicked_pdf'
And then you can simply use WickedPdf object from the application. I am not sure how your application is laid out because it does not appear to be using bundler.

Rails 4 , Heroku, PDF Generation, PDFkit

I am trying to make a flyer creator app and am having a hard time getting the page to save as a pdf.
After doing a bit of googling I found a couple options and landed on pdfkit. The rails casts video made it look very simple, then like always, being on a windows machine, I found it didn't exactly apply. I have tried a ton of tutorials but am still unable to get my local environment working.
I eventually would like to deploy this solution to heroku and that seams to also require some extra steps.
My gems include,
gem "pdfkit"
my application.rb includes
config.middleware.use "PDFKit::Middleware", :print_media_type => true
I have in my /config/initializers I have pdfkit.rb that contains
PDFKit.configure do |config|
config.wkhtmltopdf = 'C:/wkhtmltopdf/bin/wkhtmltopdf.exe'
config.default_options = {
:page_size => 'Legal',
:print_media_type => true
}
end
Is there anything else needed I may have missed?
I have seen the gem "wkhtmltopdf-binary" referenced in some tutorials, do I need this gem? what is it doing?
I have installed the wkhtmltopdf application all over my computer at this point, I saw one tutorial that placed the install in the actual root of the app, in the root of my C: drive and elsewhere. Even when I think I got this part right at best I got the message
"Exit with code 1 due to network error: ContentNotFoundError"
I would really like some help getting PDFKit to work on my local environment, and then deploy that solution to heroku. Can anyone help?
I can show any code snippets needed I am just unsure what would be helpful.
In case it helps anyone here is a link to my work in progress site / an example page that I would like turned into a pdf.
http://www.easyflyerceator.com/carpet_cleaning_flyers/1/carpet_cleaning1s/4
Problem is with wkhtmltopdf.exe path in pdfkit.rb, move your binary file to bin folder of the project(Create one, if it’s not there. You can create any other folder too but then remember to change the path in the initializers.) and then specify same path in pdfkit.rb as follow:
PDFKit.configure do |config|
config.wkhtmltopdf = Rails.root.join('bin', 'wkhtmltopdf').to_s
config.default_options = {
:page_size => 'Legal',
:print_media_type => true
}
end
You can refer Converting HTML to PDF.

how to require "prawn/measurement_extensions" in rails

I wrote some demo code in ruby with prawn and want to move this code into my rails app
In the ruby code i use the measurement_extensions for prawn:
require "prawn/measurement_extensions"
In my rails app i put the same line into my controller, but this provoces an error:
cannot load such file -- prawn/measurement_extensions
So whats wrong?
You could make your rails ruby file inherit from Prawn::Document and require the extension within it e.g.
class NameOfClass < Prawn::Document
require "prawn/measurement_extensions"
#code
end
From the prawn documentation:
Add prawn to your Gemfile:
gem 'prawn'
Install:
$ bundle install
Create a file called config/initializers/prawn.rb and in it, add one of the following lines, depending on your Prawn version:
Prawn through 0.8.4:
require "prawn/core"
Prawn 0.9+ or git:
require "prawn"
Now, Prawn should be ready to go.

How to package application layout into a Ruby gem?

I'm working on a project comprising three different applications. They are supposed to share some models and the outer layout. To avoid code duplication, I'm trying to extract the application layout (project_name/app/views/layouts/application.html.haml) into a gem.
I followed these steps:
create the base gem structure with bundle gem common
place the layout file inside common/app/views/layouts/application.html.haml
wrote the Gemspec descriptors
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/common/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Arthur Alkmim"]
gem.email = ["myemail#here"]
gem.description = %q{Common project files}
gem.summary = %q{Common project files, including layout and migrations}
gem.homepage = ""
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "common"
gem.require_paths = ["lib"]
gem.version = Common::VERSION
end
commit the changes
gem build common.gemspec (successful)
rake install (successful)
Place gem 'common' in the project Gemfile
But still the project won't load the application layout. What should I do to tell my project it has to load the layout files through the gem?
Thanks in advance.
Have you added your gem to your Rails Gemfile to include it in your application?
You can use the path option to specify a relative path in development. e.g.
gem 'common', :path => "../path/to/gem"
Don't forget to then run bundle install
I sort of solved it. I changed application.html.haml to common.html.haml and placed the relevant layout call in the ApplicationController. Seems like Rails won't let me package the application.html layout in a gem, but other layouts are okay. If somebody comes up with a better solution (less workaround-ish), please post!

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

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 ?
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.
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

Resources