PDF Generator in rails 3 - ruby-on-rails

This code I have in the products controller Index Method:
def index
#products = Product.all
respond_to do |format|
format.html
format.pdf do
pdf = PDF::Writer.new
#products.each do |product|
pdf.text product.name
end
send_data pdf.render, :filename => 'products.pdf', :type => 'application/pdf', :disposition => 'inline'
end
end
end
and in
environment.rb file
require 'pdf/writer'
Mime::Type.register 'application/pdf', :pdf
While running the program I am getting the error
undefined method `each' for "Pen":String

Aha. According to PDF::Writer's home page, "PDF::WRITER HAS BEEN DISCONTINUED AS OF APRIL 15th, 2010. PLEASE USE ITS SPIRITUAL SUCCESSOR, PRAWN INSTEAD."
I've personally been very happy using prawn to generate PDF's. But to directly answer your question, my guess is that you're probably using ruby 1.9.x, which changed the String API a bit, and PDF::Writer is meant for ruby 1.8.7.

use metaskills-pdf-writer gem. This error is happening because the each method of strings on Ruby 1.8 has changed at version 1.9. So this no longer works on new versions of ruby. This gem i mentioned will fix the issue.

Related

Issues creating PDF using wicked and Rails API

I'm trying to create a downloadable PDF using wicked and Rails API. At the moment I can only get a PDF to download but the contents are empty and the file name is response.pdf.pdf.
This is the method I'm using to generate the PDF when a GET request is made to a specific score.
def download_pdf(score)
html = render_to_string(:action => :show, :layout => "pdf.html.erb", :template => "scores/show.pdf.erb", locals:{:score => score})
pdf = WickedPdf.new.pdf_from_string(html)
send_data(pdf,
:filename => 'test.pdf',
:disposition => 'attachment')
end
I came across this issue today. Quite late but will be useful for people looking for a solution to this.
You will have to inherit from ActionController::Base and not ActionController::API. Or you can override render_to_string with the following code.
def render_to_string(*args)
controller = ActionController::Base.new
controller.locale = I18n.locale
controller.render_to_string(*args)
end
reference: https://github.com/mileszs/wicked_pdf/issues/652

"Error: PDF could not be generated!" with WickedPDF

Error:
RuntimeError in BillsController#printing
Failed to execute:
"/usr/local/bin/wkhtmltopdf" -q "file:////var/folders/j5/2wx0qdjj7kl7vbvq3m2z4rj00000gn/T/wicked_pdf20130213-41259-x9dcb5.html" "/var/folders/j5/2wx0qdjj7kl7vbvq3m2z4rj00000gn/T/wicked_pdf_generated_file20130213-41259-mg4iqp.pdf"
Error: PDF could not be generated!
BillsController:
# GET /bills
# GET /bills.json
def print
respond_to do |format|
format.html
format.pdf do
render :pdf => "rechnung_id",
:layout => "printing.pdf",
:show_as_html => params[:debug]
end
end
end
as views I created a printing.html.erb and a printing.pdf.erb - and tried both.
I've installed wkhtmltopdf as binary and as gem. When I try to use the gem (commenting out the line:
WickedPdf.config = { :exe_path => '/usr/local/bin/wkhtmltopdf'}
something seems to crash and nothing happens..
When I use the binary, I get the error displayed on top.
The versions of my gems are:
wicked_pdf (0.9.4)
and wkhtmltopdf-binary (0.9.9.1).
I was searching for help - that's what I already tried:
"bundle update" and "bundle install"
installed wkhtmltopdf in version 9.9
added "Mime::Type.register "application/pdf", :pdf"
EDIT:
If I use the terminal and enter "wkhtmltopdf www.myHomepage.info myhomepage.pdf" it works fine. "which wkhtmltopdf" gives me the path "/usr/bin/wkhtmltopdf", but if I want to use with one, it's opening "wkhtmltopdf_darwin_386" and the website freezes..
now i solved the problem.
I changed my controller method to:
def printing
#bills = Bill.find(params[:id])
respond_to do |format|
format.html
format.pdf do
render :pdf => "bill_#{#bills.id}",
:wkhtmltopdf => '/usr/bin/wkhtmltopdf',
:template => '/bills/printing.pdf.erb',
:disposition => "inline"
#:save_to_file => Rails.root.join('pdf', "rechnung_#{#bills.id}.pdf")
end
end
end
and i had to remove WickedPDF as middleware in the application.rb:
require 'wicked_pdf'
config.middleware.use WickedPdf::Middleware, {}
now it's working as expected.

Rails 3.1 Websnap trying to generate a PNG and not getting one

I may be barking up the entire wrong tree here but in case I am not, here's a go.
I am using Websnap to generate a png file of the Show page. When I go to show.png I get a blank white page and no file downloads. It was my expectation that I would get a cute little png downloaded to my machine.
And, I get nada in the log file... not even the debug statements I put in.
Respond to code:
respond_to do |format|
format.html # index.html.erb
format.png {
#html = render :action => "show.html.erb", :layout => "application.html.erb"
snap = WebSnap::Snapper.new("/dashboard/show?application=#{#application}&version=#{#jira_version}", :format => 'png')
send_data snap.to_bytes, :filename => "dashboard.png", :type => "image/png", :disposition => 'inline'}
end
environment.rb
Mime::Type.register "image/png", :png
Turns out Websnap was having an issue finding the wkhtmltoimage executable it put on the system in the first place. I really need to rewrite that Gem.

How do I generate pdf file using Prawn in Rails?

I have used the following syntax to generate a pdf file:
Prawn::Document.generate("#{RAILS_ROOT}/public/pdf/generate.pdf") do
pdf.text "hello"
end
But when I look for the file within the /public/pdf/ folder, I dont find any file.
Well my controller code for this is
def generate
respond_to do |format|
format.pdf{ render :file => "#{RAILS_ROOT}/public/pdf/generate.pdf"}
end
end
It could be something else, but the code supplied doesn't seem to work:
Prawn::Document.generate("x.pdf") do
pdf.text "Hello"
end
gives me
NameError: undefined local variable or method `pdf' for #<Prawn::Document:0x352b6e4>
from c:/ruby/lib/ruby/gems/1.8/gems/prawn-core-0.8.4/lib/prawn/graphics/color.rb:72:in `method_missing'
from (irb):3
You should be able to see if you're getting something similar in your log file.
I think the pdf. is not needed:
Prawn::Document.generate("x.pdf") do
text "Hello"
end
ruby - 1.9.3
rails - 3.2
way 1
create new project in rails
rails new prawn_sample
you can find gem file inside project folder, add prawn gem.
gem 'prawn'
then bundle install
now, install prawnto plugin
rails plugin install git#github.com:forrest/prawnto.git
For sample data to display, let’s create a Book model with title,author and description.
rails generate scaffold book title:string author:string description:text
then
rake db:migrate
now start the server and enter sample data's to test
so,
rails s
localhost:3000/books
here enter the required amount of data's
next
Let’s get started with something simple and add a pdf version of the show action. Open up the books controller and add format.pdf
def show
#book = Book.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #book }
format.pdf { render :layout => false }
end
end
create the show.pdf.prawn file inside app/views/books. For now, lets have hello world
pdf.text "Hello World!"
visit
http://localhost:3000/books/1
http://localhost:3000/books/1.pdf
you successfully generated PDF.
Let’s make the view specific to the books.
in show.pdf.prawn
pdf.font "Helvetica"
pdf.text "Book: #{#book.title}", :size => 16, :style => :bold, :spacing => 4
pdf.text "Author: #{#book.author}", :spacing => 16
pdf.text #book.description
now you see some text with format specified above . Browse more for format you required.
way 2
Gemfile
gem 'prawn'
/config/initializers/mime_types.rb
Mime::Type.register "application/pdf", :pdf
AuditsController
def show
#audit = Audit.find(params[:id])
respond_to do |format|
format.html
format.pdf do
pdf = Prawn::Document.new
pdf.text "This is an audit."
send_data pdf.render, type: "application/pdf", disposition: "inline"
end
end
end
Not sure what version of Prawn you're using, but this worked for me:
pdf = Prawn::Document.new(background: img, :page_size => "LETTER", :page_layout => :landscape)
pdf.render_file File.join(Rails.root, "app/pdfs", "x.pdf")
I think you're missing the pdf.render_file line that actually creates the file.

Rails 3 and RJS

I use the rails 3.0.0.beta
Is there any new syntax to write RJS, here is an example
def remote_create
#photo = Photo.new(params[:photo])
respond_to do |format|
if #photo.save
# add #photo's thumbnail to last import tag
format.js {
render :update do |page|
page.insert_html :bottom, 'polaroids' , :partial => 'polaroid', :locals => {:photo => #photo}
end
}
else
#...
end
end
end
here is the screencast http://railscasts.com/episodes/205-unobtrusive-javascript
UPDATE April 2011: RJS is being extracted for Rails 3.1
prototype-rails is going to be a gem when Rails 3.1 is out
Applications using RJS have to add this line to their Gemfile while working against Rails master before the 3.1 release:
gem 'prototype-rails', :git => 'git://github.com/rails/prototype-rails.git'
more info on ruby on rails's could be found in this article
prototype-rails on github
not sure on any syntax changes for rails 3 irt rjs but i recommend following along over at railscasts.com - he's been posting videos of all the new features of rails 3 and if there are any updates on how to render/handle js i'm sure he'll do an episode on it.

Resources