How to install Wicked PDF gem in rails 3.0.0 - ruby-on-rails

Right now I am using Rails 3.0.0 version. I want to install Wicked pdf gem. I don't know how to install that gem. Please tell me that step by step procedure.

It's really easy!
Add this to Gem file!
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary', '~> 0.12.3'
Run Bundle install and run rails generate wicked_pdf
In config/initializers/mime_types.rb add this (or Uncomment)
WickedPdf.config = {
exe_path: '/usr/local/bin/wkhtmltopdf'
}
In your controller (show action)
def show
respond_to do |format|
format.pdf do
render :pdf => "file_name.pdf", :template => 'file_directory/file_name.html.erb', :encoding => 'utf-8'
end
format.html
end end
Create a erb.html file and put your pdf code in it.
In view you have to use the route controller#show for your link_to tag!
Good Luck.

use the command gem install wicked_pdf .See the documentation here. http://rubygems.org/gems/wicked_pdf & http://rubydoc.info/gems/wicked_pdf/0.7.9/frames

Reminder to restart you server after changing you config/initializers/mime_types.rb file. Other than that Afsanefda's answer worked for me.

Related

Rails 6.1.4 Wicked PDF

I am attempting to implement Wicked PDF (https://github.com/mileszs/wicked_pdf/) in a Rails 6.1.4 project and am continually getting the following error messages on the console.
My configuration is as simple as it gets. The controller looks like:
class Api::V1::ProductsController < Api::V1::BaseController
def datasheet
#product = Product.active.friendly.find params[:id]
respond_to do |format|
format.pdf {
render "products/datasheet", pdf: "datasheet-#{#product.name}"
}
end
end
end
and the datasheet.haml file looks like:
%html
%head
%body
= "This and that"
The file encoding for the datasheet.haml is UTF-8, but this shouldn't matter because the text contains no special characters.
The Gemfile has both wicked_pdf and wkhtmltopdf-binary.
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
I have executed the command rails generate wicked_pdf and it did generate the wicked_pdf.rb initializer, as expected.
I have tried putting Mime::Type.register "application/pdf", :pdf into the mime_types.rb file, but expect that this wouldn't matter because I am running Rails 6.
The response generated is:
We have another application running Rails 6.1.4 using wicked_pdf in, "ahem...", the exact same way successfully. Obviously something is different, I just cannot find out what...
Any suggestions on what I am overlooking? Your help is much appreciated!

Whois gem not working in rails

class DomaincheckerController < ApplicationController
def index
end
def store
r =Whois.whois(secure_params['domain'])
render :text => "#{r}"
end
private
def secure_params
params.require(:whois).permit(:domain)
end
end
This is my domainchecker controller. The index method renders a form. After submitting the form it goes to store method. Here I am trying to use the whois gem. I have installed whois gem by running gem install whois. But I am getting this error.
uninitialized constant DomaincheckerController::Whois
The problem is that you installed the gem directly and not using bundler, therefore the Rails app can't find the dependency.
In order to install a gem in a Rails project you need to edit the Gemfile file and add the gem there. Once added, run
$ bundle
in order to install the dependency. Check the documentation about the Gemfile.

numbers_and_words gem not working - NoMethodError in Posts#index - undefined method `to_words' for 42:Fixnum

I would like to convert some numbers in words.
So I installed the numbers_and_words gem with "gem install numbers_and_words" -
I restarted the server, and tried to run this example from the Read.me in my index.html.erb:
<%= 42.to_words %>
but I get this error:
NoMethodError in Posts#index -
undefined method `to_words' for 42:Fixnum
I checked the gem documentation a few times, but I couldn't figure out, what I am missing.
This is my posts controller regarding index.
def index
#posts = Post.order("created_at desc")
#published = Post.where(draft:false).order("created_at desc")
#drafts = Post.where(draft:true).order("created_at desc")
respond_to do |format|
format.html # index.html.erb
format.json { render json: #posts }
end
end
What did I wrong? Did I forget something in the installation process?
I am quite new to rails, sorry if this is a trivial newbie question.
Thank you so much for your help! Really appreciated.
Installing a gem is not sufficient to make it available in a Rails project. You need to add it to the Gemfile so that you can manage the dependencies with Bundler.
Edit the 'Gemfile' and add the gem
gem 'numbers_and_words'
Then run bundle again to update the Gemfile.lock
$ bundler
This will make the gem available to the app. It will also autorequire the gem on boot, if the gem uses the standard naming conventions.
It seems this gem is name correctly. Otherwise, you can explicitly require it by setting a require option in the gemfile
gem 'numbers_and_words', require: 'numbers_and_words'
If you just installed the gem locally and you didn't configure the Gemfile, the application will crash once you will deploy it.
Found a solution - not mentioned in the documentation of the gem, but it did the trick for me:
I added
require 'numbers_and_words'
in the rake file. After server restart, it's working.

wicked_pdf Error: PDF could not be generated

Gemfile
gem "wicked_pdf"
gem "wkhtmltopdf-binary"
the error:
RuntimeError in CarsController#show
Failed to execute:
/usr/bin/wkhtmltopdf --print-media-type -q - -
Error: PDF could not be generated!
Rails.root: /u/apps/zeepauto/autozeep_update
cars_controller
def show
#class_showcar = true
#class_admin = true
#car = Car.find(params[:id])
#search = Car.search(params[:search])
#cars_see_special = Car.where(:special => "1").order('rand()').limit(3)
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #car }
format.pdf do
render :pdf => "#{#car.carname.name}",
:print_media_type => true
end
end
end
show.html.erb
<p class="show_links"><%= link_to url_for(request.params.merge(:format => :pdf)) do %>
<%= image_tag('/images/printversion.png', :alt => 'Download') %>
</p>
wicked_pdf.erb
# config/initializers/wicked_pdf.rb
WickedPdf.config = {
# :exe_path => '/var/lib/gems/1.8/bin/wkhtmltopdf'
:exe_path => '/usr/bin/wkhtmltopdf'
}
I had the same problem. The solution was to add wkhtmltopdf-binary to the gem file and run bundle install.
gem "wicked_pdf"
gem "wkhtmltopdf-binary"
I had wkhtmltopdf-binary already in gemfile, but as this was working on my local computer and not on server, I left this error for the server support team to care off.. they have checked the path to wkhtmltopdf, they tried to convert a simple html to pdf and it worked.. so they tried to run a bundle update command and after this the pdf converting worked fine on server too. I had a gem path changed and I guess this was the problem. I posted my solution in case someone else will have this problem too.
For Alpine 3.9+ the wkhtmltopdf binary is available, however I was getting either a blank PDF or "Failed to load document" error - despite working fine locally on MacOSX. It turns out that you need to include fonts explicitly for alpine builds (at least)
Controller action
def show
respond_to do |format|
format.html do
render 'pdfs/templates/my_template.html.erb'
end
format.pdf do
render(
pdf: "file_name",
template: 'pdfs/templates/my_template.html.erb',
disposition: 'inline'
)
end
end
end
The above worked locally on MacOSX machine but on a server based on ruby alpine image, as below, it failed with failed to load document
Dockerfile
FROM ruby:2.6.3-alpine3.10
....
# add wkhtmltopdf for use with wicked_pdf gem
RUN apk --no-cache add wkhtmltopdf
...
even a more basic example failed with a blank pdf
respond_to do |format|
format.pdf do
pdf = WickedPdf.new.pdf_from_string('TESTING 123')
send_data(
pdf,
filename: "file_name.pdf",
type: 'application/pdf',
disposition: 'inline'
)
end
end
Solution
Dockerfile
FROM ruby:2.6.3-alpine3.10
....
# add wkhtmltopdf for use with wicked_pdf gem
RUN apk --no-cache add \
ttf-ubuntu-font-family \
wkhtmltopdf
...
Ideally Alpine would include a basic font with the wkhtmltopdf package, however until such time I found this to be a useful source of info and/or good for adding a mutistage Docker file.
https://github.com/madnight/docker-alpine-wkhtmltopdf/blob/master/Dockerfile
NOTE:
lack of an explicit font package in alpine may also cause PDF conversion using libreoffice to fail too. We found corrupt PDFs when converted from docx files in particular.
I had the same problem. I had wkhtmltopdf-binary installed and bundle update didn't help neither. Here is what helped me:
The important thing is that I run this on Alpine Linux and it does not seem to be supported by gem wkhtmltopdf_binary_gem https://github.com/zakird/wkhtmltopdf_binary_gem/issues/53
I installed separately wkhtmltopdf into the system: apk add wkhtmltopdf
And then edited the initializer to include the binary path:
# config/initializers/wicked_pdf.rb
require "wicked_pdf"
WickedPdf.config = {
exe_path: ENV["WKHTMLTOPDF_BIN"]
}
I'm facing the same issue, it works fine on local machine but when deployed on the server it raises an error:
Error: PDF could not be generated!.
In my case, there are some dependencies missing on the server. Use the below command on the server to install the dependencies.
sudo apt-get install libfontconfig1 libxrender1
I have the same problem when using Ubuntu 20.04.
I solve the problem by using wkhtmltopdf-binary version 0.12.6.1.
If you are facing this in the docker container, most probably, you are using the Alpine Linux. In that case, wkhtmltopdf-binary is not compatible with the Alpine Linux. So, add these gems instead:
gem 'wicked_pdf', github: 'mileszs/wicked_pdf'
gem 'wkhtmltopdf-binary-edge-alpine', '~> 0.12.5.0'
wkhtmltopdf-binary-edge-alpine is for the Alpine Linux. Everything should work just fine, hopefully😂

pdfkit does not style pdfs

I have a rails 3.1 app that creates pdf documents using pdfkit, and everything works as specified, except for the fact that the generated pdfs don't have any styling. I am assuming that wkhtmltopdf doesn't have access to my stylesheets and that it is not a larger issue than that. Would anyone have a clue as to how you would allow access to these stylesheets? I have basically followed railscast #220 on the subject, however I have had to create a new initializer to get pdfkit to work with rails 3.1.
This is the initializer that I had to use to get pdfkit to work with rails 3.1
ActionController::Base.asset_host = Proc.new { |source, request|
if request.env["REQUEST_PATH"].include? ".pdf"
"file://#{Rails.root.join('public')}"
else
"#{request.protocol}#{request.host_with_port}"
end
}
The link to the pdf looks like this:
<%= link_to 'Download PDF', load_path(#load, :format => "pdf") %>
This will give me a link to the pdf that has no styling.
In my application.rb I have configured pdfkit as such:
config.middleware.use PDFKit::Middleware, :print_media_type => true
I have also added this to my layouts/application.html.erb file:
<%= stylesheet_link_tag "application", :media => "all" %>
Stealing a couple of lines from the middleware code found at https://github.com/pdfkit/pdfkit/blob/master/lib/pdfkit/middleware.rb
You can use:
root = PDFKit.configuration.root_url || "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/"
html.gsub!(/(href|src)=(['"])\/([^\"']*|[^"']*)['"]/, '\1=\2' + root + '\3\2')
My example is:
html = render_to_string #render current action to string
root = PDFKit.configuration.root_url || "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/"
html.gsub!(/(href|src)=(['"])\/([^\"']*|[^"']*)['"]/, '\1=\2' + root + '\3\2')
kit = PDFKit.new(html, :print_media_type => true)
For me it was problem with installation for ubuntu. I just reinstalled from source:
# first, installing dependencies
sudo aptitude install openssl build-essential xorg libssl-dev
# for 64bits OS
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-amd64.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2
mv wkhtmltopdf-amd64 /usr/local/bin/wkhtmltopdf
chmod +x /usr/local/bin/wkhtmltopdf
# for 32bits OS
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-i386.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-i386.tar.bz2
mv wkhtmltopdf-i386 /usr/local/bin/wkhtmltopdf
chmod +x /usr/local/bin/wkhtmltopdf
And everything works now for me. So my advice is do not install wkhtmltopdf by this command sudo apt-get install wkhtmltopdf and install it from sources. Full instructions
for installation process
I know you're looking for solution that will render whole page, just reminder for googling people that there is still problem free workaround
class DocumentController < ApplicationController
def show
#document = Document.last
# ... implement your respond_to
kit = PDFKit.new(#document.content, :page_size => 'Letter')
kit.stylesheets << "#{Rails.root}/app/assets/stylesheets/pdf.css"
send_data kit.to_pdf, :filename => "#{#document.title}.pdf", :type => 'application/pdf'
end
end
now the pdf.css must be css, so teoretically if you need to load sass load it from pre-compiled public/assets/
I ran into this problem as well, and it appears that when the asset pipeline was added in Rails 3.1, pdfkit has a problem with the stylesheet links. See the GitHub issue about this problem.
I ended up switching to wicked_pdf and am really happy with it. They've solved this problem and it works nicely on Rails 3.2.x (haven't tried 3.1.x).
I have used gem 'wicked_pdf' and its helpers to include CSS into pages. Internally that helpers just read all CSS files and include into the page itself. So if you prefer to use PdfKit try to investigate how to include non-inline stylesheets.
I have successfully run PDFKit on Rails 3.1. I have used a different setup though.
At first I had the same problem you did but that was because stylesheet_link_tag has a default set to media => "screen"; specifying explicitely media => "all" fixed it.

Resources