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!
I am trying to implement the gem wicked_pdf . After initial difficulties (fatal error (exception reentered)), I managed to start the server. I set up a pdf with the content "Hello world" for the test, but every time I want to open it, I get a "failed to load PDF document" notification
Controller
def index
respond_to do |format|
format.html
format.pdf do
render pdf: "index.pdf.haml",
layout: 'pdf.html.haml',
page_size: 'A4',
disposition: 'inline'
end
end
end
index.pdf.haml
Hello world
config/initializers/wicked_pdf.rb
# WickedPDF Global Configuration
#
# Use this to set up shared configuration options for your entire application.
# Any of the configuration options shown here can also be applied to single
# models by passing arguments to the `render :pdf` call.
#
# To learn more, check out the README:
#
# https://github.com/mileszs/wicked_pdf/blob/master/README.md
class WickedPdf
module PdfHelper
remove_method(:render)
end
end
WickedPdf.config = {
# Path to the wkhtmltopdf executable: This usually isn't needed if using
# one of the wkhtmltopdf-binary family of gems.
# exe_path: '/usr/local/bin/wkhtmltopdf',
# or
# exe_path: Gem.bin_path('wkhtmltopdf-binary', 'wkhtmltopdf')
# Layout file to be used for all PDFs
# (but can be overridden in `render :pdf` calls)
# layout: 'pdf.haml',
# Using wkhtmltopdf without an X server can be achieved by enabling the
# 'use_xvfb' flag. This will wrap all wkhtmltopdf commands around the
# 'xvfb-run' #command, in order to simulate an X server.
# use_xvfb: true,
}
config/initializers/mime_types.rb
# frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
Mime::Type.register "application/pdf", :pdf
Link to Screenshot: https://drive.google.com/file/d/1ujt8ANq16SrmSHJk45APMXXxm1l5q5ic/view?usp=sharing
Ok, so I downgraded wicked_pdf to version 1.4.0 and I removed:
class WickedPdf
module PdfHelper
remove_method(:render)
end
end
From config/initializers/wicked_pdf.rb, and now it works.
I have been banging my head against this for several days. Recently, my image uploader has stopped working properly. I have investigated several possibilities, but have none of the suggested solutions have worked in my case.
The error message is:
#<Paperclip::Errors::NotIdentifiedByImageMagickError:Paperclip::Errors::NotIdentifiedByImageMagickError>
Here are the details:
Mac OS X 10.8.3
ImageMagick 6.8.4-4 2013-03-29
libtool => /usr/bin/libtool
Rails 3.2.13
Ruby 1.9.3p194
development.rb contains appropriate path (and I have verified that it is correct using which identify)
Paperclip.options[:command_path] = "/usr/local/bin/"
Gemfile.lock (relevant portion)
paperclip (3.4.1)
activemodel (>= 3.0.0)
activerecord (>= 3.0.0)
activesupport (>= 3.0.0)
cocaine (~> 0.5.0)
MODEL (I am updating a classroom object, but the picture resides in the location model. (Classroom has_one :location, :as => :locatable)
Model location.rb
class Location < ActiveRecord::Base
## Paperclip method for uploading location images
has_attached_file :picture, :styles => {:show => "1200x500#", :medium => "300x300#", :thumb => "100x100>"}, :convert_options => {:show => "-gravity center"}
has_attached_file :building_sign, :styles => { :show => ["1200x500#", :jpg], :medium => ["300x300#", :jpg], :thumb => ["100x100#", :jpg] }, :convert_options => {:show => "-gravity center"}
belongs_to :locatable, :polymorphic => true
belongs_to :location_type
validates :name, :presence => true
validates :latitude, :presence => true,
:length => {:within => 9..18},
:numericality => true
validates :longitude, :presence => true,
:length => {:within => 9..18},
:numericality => true
end
Controller classrooms_controller.rb
def update
#classroom = Classroom.find_by_facility_code_heprod(params[:id].upcase)
respond_to do |format|
if #classroom.update_attributes(params[:classroom])
format.html { redirect_to(#classroom, :notice => 'Classroom was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #classroom.errors, :status => :unprocessable_entity }
end
end
end
What I've tried.
I've made sure that the image name is simple (USB2230.jpg), no colons.
I've updated the version of ImageMagick to the most recent.
I've also re-downloaded and reinstalled the CommandLine Tools for 10.8.3 (someone suggested that the issue might be related to an outdated libtool).
I've rebooted the computer.
I've tried variations on gem versions including
# variation 1
gem 'paperclip', '~> 2.8.0'
gem "cocaine", "=0.3.2"
# variation 2
gem "paperclip", "~> 3.4.0"
gem "cocaine", "= 0.4"
# variation 3 (which is what is reflected in the included Gemfile.lock info above).
gem "paperclip", "~> 3.4.0"
If I remove the scaling,
:styles => {:show => "1200x500#", :medium => "300x300#", :thumb => "100x100>"},
:convert_options => {:show => "-gravity center"}
the upload works, but I kind of need the scaling ;-)
Can anyone see something I am missing?
We just ran into this issue, and it turned out to be an issue where ghostscript wasn't installed. I took the advise of Scott Cornwell and removed the silencing of errors, and then determined that convert was failing because ghostscript wasn't available.
brew install ghostscript
Fixed the issue for us.
I had the same issue, although my server is on Linux. Can't tell you exactly how to do it because I don't have a Mac to test, but hopefully this points you in the right direction.
This worked for me with ImageMagick 6.8.5-5, Paperclip 3.4.2, latest version of cocaine, Rails 3.2.13:
I went into geometry_detector_factory.rb in the Paperclip gem and commented out the 2 lines around the identify call: (this step is not necessary, just explaining what I did to determine the problem)
#silence_stream(STDERR) do
Paperclip.run("identify", "-format '%wx%h,%[exif:orientation]' :file", :file => "#{path}[0]")
#end
along with the corresponding "end" statement. This allowed me to see the errors on the command line when running the "identify" command.
Basically the error said: "no decode delegate for this image format"
You can probably look up that error and get it figured out, but basically what I did was go to usr/local/bin and run: (also not necessary, unless you want to see what you have installed)
convert -list configure
and look for the DELEGATES line. I had another Linux server where ImageMagick was working and after comparing the two I realized the new one had only 2 delegates installed. I was able to run:
yum install ImageMagick-devel
and then recompile ImageMagick with make, make install and it worked.
You can also find the delegates manually on the ImageMagick site and install them one by one but that library pretty much covered it for me.
Debugging ImageMagick? Ain't nobody got time for that!
Had the problem on my window dev environment, using paperclip 3.5.2, cocaine 0.5.3, and ImageMagic 6.8.8.
Solution was to add:
Paperclip.options[:command_path] = 'C:\Program Files\ImageMagick-6.8.8-Q16'
to config/environment/development.rb
I had similar issue, but older PaperClip (3.0.2).
In my case I fixed it with:
gem 'cocaine', '0.3.2'
I just solved this issue.
brew makes a directory call Cellar, /usr/local/Cellar
Verify if you don`t have two ImageMagick, i had one named ImageMagick-Ruby182, so, if you have it run brew uninstall ImageMagick-Ruby182, and also the normal imagemagick, and reinstall image magic.
Reinstalling libtool brew install libtool worked for me.
Please update the version of paperclip gem and cocaine gem.
Set PaperClip version: 3.4.1
Set Cocaine version: 0.5.
I faced the same problem and my issue was already there in paperclip gem github issues
You already mentioned that you tried upgrading ImageMagick, but I had the same issue and upgrading to ImageMagick 6.8.0-10 2013-03-03 fixed it for me.
Had same issue with image_magic that was breaking our paperclip functionality in production, but not in development (weird, I know).
Yet even after removing imagemagick from our gemfile and Gemfile.lock locally (running bundle install and all that stuff) and then deploying back to production on heroku, the error persisted in production! (weird, I know).
What ended up doing the trick was running:
$ heroku repo:purge_cache -a myAppName
(Taken from: https://github.com/heroku/heroku-repo#purge_cache)
When you deploy your app, Heroku caches some things like your assets and installed gems in order to speed up deployment.
Although this is a great feature, it can have side-effects sometimes, and in this case, it seems that something about the imagemagick gem got "stuck" in production's cache, which is why purging solved the issue for us (since after purging, your app will rebuild itself from scratch on your next deployment)
I have the same issue, and I solved it, when i configure the dynamic linker run-time bindings to create the necessary links and cache to the most recent shared libraries using the ldconfig command.
So you need to use the following command:
sudo ldconfig /usr/local/lib
Actually, I advice to re-install imagemagick using steps at how-to-install-image-magick-and-setup-paperclip.
Just for the record:
brew uninstall libtool
brew install libtool
brew uninstall jpeg
brew install jpeg
brew link --overwrite jpeg
brew unlink freetype && brew link freetype
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.
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.