#153 PDFs with Prawn
Mar 16, 2009 | 10 minutes |
Plugins
Prawn is an excellent Ruby library for generating PDF documents. Learn how to use it along with the Prawnto plugin in this episode.
- Download:
- source codeProject Files in Zip (121 KB)
- mp4Full Size H.264 Video (14.6 MB)
- m4vSmaller H.264 Video (10.2 MB)
- webmFull Size VP8 Video (27.7 MB)
- ogvFull Size Theora Video (20.4 MB)
I made it for the first time to be the first. Nice cast Ryan, helped me a lot. But does this work with the XFA forms??
Great screencast. This looks like a much cleaner/nicer way to generate pdfs, plus the tip about formatted path being taken out is helpful (I forgot about that myself).
@Millisami Are "XFA forms" the interactive forms that you sometimes see in PDFs?
If so, no. Prawn does not current support adding them to your PDFs. There was a discussion on forms on the prawn mailing list a couple of days ago though.
Thanks, Ryan
I've used it before and like it so far.
It's so good to see that you suggesting it too.
It mean that I've made good choice :)
Thanks and have a good week ahead!
;)
**NOTE:
You also will need format.pdf in the controller.. just thought I would add that.
@Mephux
Ryan told that it's not required.
Thanks a lot for making this Ryan. Hopefully we'll see lots of people joining up on the mailing list with any questions they might have:
http://groups.google.com/group/prawn-ruby
Anyone know some good tool for read(parse) pdf files?
Thanks for another great video Ryan!
@Alexei
Was for me on 2.3.1.. hhmm wonder what the issue was then.
Excellent screencast, thanks. Does anybody know how to merge PDF files in Prawn? I have created PDF (in Illustrator), which I want to use as cover for my generated PDFs. Thanks
@Daniel
http://github.com/yob/pdf-reader
and
http://github.com/sandal/pdf-inspector
@Powerplant,
We don't support PDF merging yet (and it's not planned for the near future), but you probably shell out to pdftk for that:
http://www.accesspdf.com/pdftk/
@mephux, I should have clarified this in the screencast. If you already have a respond_to block in the controller, then you will need to add a format.pdf line. Otherwise Rails should automatically handle this.
Thank you for this (as usual) amazing screencast.
I have a question. Is there a way (with Javascript maybe ?) to send to the printer the pdf, directly from the web page (and not generate the PDF and select "print" on the PDF reader) ?
What I want is more or less a button (or hyperlink) on a webpage called "print". It generates pdf but it is hided to the user.
Great screencast, Ryan! Very timely for me, as I was implementing this very thing in one of my apps last week. If Prawto's documentation had been _half_ as easy to understand as this, it would have saved me a lot of frustration. :)
For some reason my PDF is not rendering. in my log i get "406 Not Acceptable" error.
i've tried it with Rails 2.3.1 & 2.3.2.
Please help.
in your controller:
def show
respond_to do |format|
format.html # show.html.erb
format.json { render json: @order }
format.pdf { render :layout => false }
end
end
@Rajesh
You need to have "format.pdf" in your controller for the method you're doing this on. Like Ryan said earlier, you only need that if you already have a format block in your controller already.
Hi Mark, Thanks. I was using the make_resourceful plugin and didn't think i needed the format.pdf option.
Thanks for your help
Thank you Ryan for all the screen casts :)
I second the thanks. Your screen casts are the coolest way to learn.
Thanks! I've got to say I really like the plugin screencasts, like this one, a lot more than the new rails features ones!
I'm tryin' to install plugin, but got this error:
Plugin not found: ["git://github.com/thorny-sun/prawnto.git"]
(Rails 2.3.2, Ruby 1.9.1p0)
Thanks Ryan.
Hi Ryan,
Great podcast (as usual)... I got to say that although I love the fact that it is easier to generate PDF files I'm kinda torn by the need to "code" the actual look and feel of that PDF file whereas with web application we get the benefit of the CSS and such.
Any idea on how we could use an approach similar to HTML+CSS when generating our PDF?
Thanks for the episode!
I was curious how to output unicode characters into the pdf, until found it to be really easy - what matters is only the font file, which can be put somewhere under rails root and pointed by pdf.font method.
http://pastie.org/419177
Ryan, this is awesome. Can you also over SSL Certificates and how to integrate them with your application when processing credit cards? that would be awesome.
@Jean-Marc
HTML/CSS -> PDF is hard and the only solutions that I know of that work reliable are Prince XML (expensive) and HTMLDOC (GPL, and not very flexible)
However, for basic styling needs, you might be able to get some love out of prawn-format:
http://jamis.github.com/prawn-format/
@Alexander
About ./script/plugin not working :
http://rails.lighthouseapp.com/projects/8994/tickets/2018-ruby-19-compat-plugininstall-git-always-fails-in-ruby-19
I haven't even watched it yet, but I know I'm gonna love this one. I've had my eye on Prawn for an upcoming project, and I'm hoping it'll best the previous pdf-writer library.
Thanks again, Ryan!
@jhc_
Thank you! It works for me
I've been took a look in prawn and rghost, I haven't choose one yet. I like prawn but rghost is easier but I need the ghostscript in the server.
@Thiago:
What specifically is rghost nicer for? I asked for feedback on what we should steal from it a while ago :)
When ever I create a new invoice I'd like to send an e-mail to the client with that invoice attached as a PDF. I know how to send an e-mail and I now how to generate a PDF. But I don't know how to magically attache that very same PDF to the e-mail. I have to attache the PDF because the rails app is not reachable from the internet. Any ideas on this?
Great screen cast, Ryan!
Came just in time when I needed it! :)
@Gregory
Basically I like: work with tags, put a eps in background and write data over the image because eps keep the resolution and filters(before_page_create, even_pages and something like that)
@Thiago,
custom tags can be built with Prawn::Format. EPS support is a 'would-be-nice' feature, but I haven't had a need for it just yet. You can background a JPG or PNG in Prawn, but it does have that resolution issue.
The page based filters will be in Prawn 0.5, porting the repeating page elements interface from PDF::Wrapper.
So if you like those features, keep an eye on Prawn for changes between now and 1.0. While I can't promise we'll hit them all, at least some will be addressed.
After installing prawn and prawnto I now get this error when I try and run the server.
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:275:in `load_missing_constant': uninitialized constant ActiveSupport::Memoizable (NameError)
Does anybody have any clues for a newbie.
Thanks
Richard
Hi Ryan,
Nice screencast :).
Im getting the same error as Richard above.. i too have ActiveSupport 2.1.0.
Should I be using an older version of prawnto or prawn?
I do not want to upgrade Rails.
For those who get the above error,
the author of prawnto extends the Memoizable class of ActiveSupport 2.2 to memoize a couple of methods.
Commenting out the following lines from /vendor/plugins/prawnto/lib/prawnto/template_handler/compile_support.rb
should get things rolling..
-extend ActiveSupport::Memoizable
-memoize :ie_request?
-memoize :ssl_request?
Great railscast, helped me get started with Prawn.
One Issue I had was using some of the Prawnto features such as bounding_box or any other item on:
http://www.cracklabs.com/prawnto/demos
I added the prawn.rb and folder to my lib directory then put your tutorial inside of:
pdf = Prawn::Document.new do
end
and was then able to use all of these features, you do have to put any variable declaration outside of this block though.
Here is some of my test code:
http://pastie.org/429045
What is the best way to auto-trigger the print button/action in Rails? So that 1). the PDF is generated and displayed on the screen via prawn/prawnto and 2). the printer selection pop-up is automatically displayed. Any help would be greatly appreciated.
Hi! Thanks for the cast. But I found one sad thing for me - no support of other languages. I have russian strings in utf8 and prawn writes them as '______'. I think this is the font problem, but I did not found a solution. Any ideas?
Awesome! But where did you get the textmate bundle? I've been looking all over for it. My textmate doesn't color my .pdf.prawn files and dangit, I'm jealous!
Thanks for the cast. Excited about using Prawnto but I'm having trouble installing the plugin. When ever I run the command it says:
removing: .../vendor/plugins/prawnto/.git
sh: git: command not found
Any help for the noob?
Thanks
Thanks for the screencast! I only have one issue. I'm making a school website where students can type there reports online. I'm using tinymce as editor, but tiny stores the text as HTML in the database.
When I display this text in PDF you see all HTML tags. How can I remove these ???
Thanks..
Jeremy: git is a version control system. You will have to install it before you can clone from github. It doesn't take long.
I'd still like to know where I can find the textmate bundle for coloring my prawn files...
Always love the screencasts Ryan. I have rails 2.2.2 I installed the gem and plugin fine but when I just add a views/show/calls.15.pdf file which at this point is just a text.pdf "Hello world" and point my browser to it It doesn't even open the file so give me the show page "Hello world". I jump to the Acrobat app - it asks if I want to open the file and then it says it is not supported when I try to open it. I get nothing like the screencast. do I need to update rails? Thanks
Every time i try to install the plugin i get the following line:
removing: C:/rails/rails_apps/QTI/vendor/plugins/prawnto/.git
I am using this:
ruby script/plugin install git://github.com/thorny-sun/prawnto.git
any hints?
A friend and a business partner of mine, Wojciech Piekutowski, wrote gem that makes Prawn faster by using ImageMagick for PNG processing. You can find it on github: http://github.com/amberbit/prawn-fast-png/tree/master
does anyone has prawn and prawnto successfully running under rails 2.3.2? i'm getting a "Template is missing" error. Same error applies here (http://www.nabble.com/Prawn-%2B-PrawnTo-%2B-Rails-2.3.2-td22720589.html)
Hello, is there a way to using rails-layouts with prawn? I'll render a pdf-page with :layout => "pdf_letter" and inside this layout I using yield. But this will render a pdf file inside the pdf letter layout and is not showing.
There a an example to using prawnto like erb files and layouts in rails?
Thanks Ryan. This cast did a great job at helping to jumpstart my usage of Prawn. It's a very useful library.
Anyone know why my request to join the prawn Google group was not approved?
Ryan,
Thanks for the screencast. A couple of things that aren't covered in the screencast
1. Add the following to environment.rb : config.gem "prawn"
2. You may also need to add the following to your controller for the appropriate actions
respond_to do | format |
format.pdf { render :format=>false}
end
Johannes:
I have it working fine in latest version.
hi ryan,
thx for answer. I found the bug couple of seconds ago: the prawnto-plugin wasn't installed correctly. I had an empty folder, instead of the plugin-sources. So I downloaded a zip version of prawnto, copied into my plugin-folder and restarted the server. now it's working ... ;)
Hey Samo,
The syntax highlighting is the same as ruby highlighting since you are essentially using ruby to write pdfs in the prawn files. To get the syntax highlighting just click at the bottom where it says "Plain Text" and switch it to Ruby.
Hello Ryan,
The plugin is really nice.But when I tried to show an image inside a table it shows both the image and the array object.Can you please help me in removing the array object and show only the image.
Here is my code
items= @products_site.select{|site| site.category_id == category}.map do |site|
[pdf.image("#{RAILS_ROOT}/public/images/message.jpg"),
site.product.barcode,
site.product.name,
number_to_currency(site.price)]
end
pdf.table items,:border_style=>:grid, :row_colors => ["FFFFFF","EFEFEF"],
:headers => ["IMAGE","ISBN", "TITLE", "PRICE"],
:align => { 0 => :center, 1 => :center, 2 => :center, 3 => :center,4=>:center,5=>:center },:border_width => 0.04,
:width=>500
end
I got the same error as Alexander.. Had a look at the patch, but don't know how to implement it. Help anyone?
Great webcast! I need to produce several different documents from the one model. For example, off my "contact" model I want to have several letters. "Welcome", "Happy Birthday" etc etc. Can this be done with this method, or is there a 1-1 relationship between a view and a pdf??
Is there a way to use rails-layouts with prawn(to)?
Something like:
render foo.pdf.prawn :layout => "default.pdf.prawn}
My example don't work (it's render the foo.pdf inside the default.pdf). :-(
Doesn't work for me, and I don't know why :S
When I add .pdf in my browser it gives me an empty page. In my log I'm getting a 406 error.
All I did was install Prawn and Prawnto, I made a show.pdf.prawn and added pdf.text "Hello".
So any ideas ?
in your controller:
def show
respond_to do |format|
format.html # show.html.erb
format.json { render json: @order }
format.pdf { render :layout => false }
end
end
bryan, try adding "format.pdf" in your respond_to block.
I saw this post http://www.hashcode.eti.br/?p=282 the comparative pdf-writer, prawn and rghost, it was created by RGhost's author, very interesting result but I prefer Prawn, it's pure and works fine for my projects :)
What would the route in routes.rb look like for this?
I am using namespaces in my project which is forcing me to have stricter routing, and don't konw how to route for the .pdf in Rails.
I mean what would the action be if I added this to a routes entry?
I know what my controller would be, but not an action.
Anyone have any ideas?
If you wanted your textmate bundles to make your prawn files all preaty to look at then here is what you need to do.
Goto bundles/bundle editor/show bundle editor note that is not a file path that is the path to the bundle editor when in text mate.
after that you just need to go to ruby tab and go all the way to the bottom until you see the words ruby. Just click it and then you will see the mountain of text that you can edit.
Edit this peace "fileTypes = ( 'rsel', 'rb', 'rbx )" so that it includes the file extention of prawn.
fileTypes = ( 'rsel', 'rb', 'rbx', 'rjs', 'Rakefile', 'rake', 'cgi', 'fcgi', 'gemspec', 'irbrc', 'capfile', 'prawn' )
Thijs de Vries,
Thanks for the tip. However, I've switched to vim since I posted my question about syntax highlighting. I've been searching for an easy way to tell vim to consider a pdf.prawn file as ruby code, but I can't seem to find anything. Any help is appreciated :)
The option to set the width of cells in a table has been changed from :widths to :column_widths in Prawn 0.4
I haven't seen this documented in the examples at http://www.cracklabs.com/prawnto , hope this helps!
Deb
some newbies problems and solutions:
1) impossible to download prawn or prawnto: try again ! I need to do this 5 times
2) Error with Memoizable: Comment the 3 related lines in compile_support.rb
3) Blank page => be sure to have this line in respond_to format in your controller: format.pdf { render :layout => false }
Hi
Thanks Ryan for the screencast.I have the problem with autosizing the cell My table has three columns And if the third cell content is very big, suppose a lengthy email then the content overflows from cell to right margin of pdf Could you please tel how can I control this? My example code is
[
c.full_name,
'sales admin, purchase admin, stores controller,store keeper,sales admin, purchase admin', 'test.....@test.com']
pdf.table contact_data,
:border_color => "DDDDDD",
:headers => ["Name", "Roles","Email"],
:border_width => 3,
:align => { 0 => :left, 1 => :left, 2 => :left }
hello i am using this cast for my application but am getting some error near
prawnto :prawn => { :top_margin => 75 }
like undefined method `prawnto'
if dont put prawnto it gave me missing layout error
please help me
I kept getting odd errors from Firefox like:
File can't be saved because source file can not be read.
IE seemed to work fine, oddly enough. I specified a filename for the pdf in my controller and that fixed the problem with Firefox.
"prawnto :filename => 'foo.pdf'"
Hi guys,
Could anybody please tell me how to use bullets with my text?
Thanks
When doing java development I used to use flying_saucer. In my last app I used jruby along with wycats-ufo for seamless ruby integration with flying saucer. It's a dead simple 1 method call to make a pdf. I would recommend it to anyone that would consider running on jruby. At least even a small service to just generate the pdf's.
Everything works perfect for me except one thing. Is it possible to include the page number in the pdf as "Page n of n" I can get the current page but I haven't been able to find a way to get the total number of pages.
Hi
ruby script/plugin install git://github.com/thorny-sun/prawnto.gi not working for me iam using rails 2.3.2 on windows xp.any solution?help me
Hi Ryan Nice artical.It worked for me when i take
@attendence= Attendence.find(:all)
but when i take
@attendence= Attendence.find(:all,:conditions => ["date >= ? AND date <= ? AND grade=?",params[:start_date],params[:end_date],params[:grade]])
not displaying values in pdf file.In show.html.erb the values are displaying correctly.please tell me how can i take:Here is my code:
controller:
def show
@attendence= Attendence.find(:all,:conditions => ["date >= ? AND date <= ? AND grade=?",params[:start_date],params[:end_date],params[:grade]])
end
show.pdf.prawn
pdf.text " Attendence Report", :size => 30, :style => :bold
pdf.move_down(30)
@attendence.each do |attendence|
pdf.text attendence.date
end
Is it possible to set one of the columns in the table to use a different type of font than the rest?
@Stefan (#33):
You can save the file in your view (not really pretty, I know ...)
pdf.render_file "tmp/example.pdf" #relative to RAILS_ROOT
is there any way to make footers work when printing multi-page table?
Instead of using:
order_path(@order, :format => 'pdf')
I prefer to create a helper method like this
def pdf(path)
path + '.pdf'
end
and then call on the view
pdf(order_path(@order))
this way the url will look like you are pointing to a stored file instead of a pdf generator.
Cheers
After installing prawn and prawnto I get this error when I try and run the server.
D:/Redmine/redmine-0.8.7/vendor/rails/activesupport/lib/active_support/dependenc
ies.rb:276:in `load_missing_constant': uninitialized constant ActiveSupport::Mem
oizable (NameError)
next I Commenting out the following lines from /vendor/plugins/prawnto/lib/prawnto/template_handler/compile_support.rb
like this
#extend ActiveSupport::Memoizable
#memoize :ie_request?
#memoize :ssl_request?
but I get the different error message.
D:/Redmine/redmine-0.8.7/vendor/plugins/prawnto/lib/prawnto/template_handler/com
pile_support.rb:32: undefined method `memoize' for Prawnto::TemplateHandler::Com
pileSupport:Class (NoMethodError)
THX for this gr8 tutorial Ryan!
Q: How can I set the table headers bold with the inline prawnto?
Hi! I really enjoy to use prawn + prawnto but have one problem:
My PDF (Rails 2.3.1, Prawn 0.6.3, Prawnto, prawn-core, prawn-format, prawn-layout) is generated from a prawnto-template and gets data from a from which also produces csv, so the parameter format pdf is added in a method which will be called before generating the pdf. The produced PDF has no file extension. How to solve this problem? Tried already respond_to block, but did not help.
Thx, Sandra
I found a solution:
prawnto :filename => 'filename.pdf'
Thx, Sandra
I am running ruby 1.9 in xp and I cannot load the plugin it says
***** plugin not found
[git://github.com/thorny-sun/prawnto.git]
Please help
If your having problems installing from got on windows use the http-readonly url rather than the git one.
I had problems with the prawnto gem not loading, so it might be worth checking what you've got in your environment.rb for the config.plugins if you don't have :all you'll need to remember to add :prawnto
Also, the file.pdf.prawn needs to end with an empty line, otherwise there will be a compile error. Running Rails 2.3.5 Ruby 1.8.6 on WinXP. I had trouble downloading the plugin also. Simple way is to download the zip file and unzip it into the vendor/plugin/prawnto folder of your rails application. http://github.com/thorny-sun/prawnto/zipball/v2.0
I was having trouble creating a pdf.table with ruby 1.8.6 on rails 2.3.5 I kept getting a NoMethodError undefined method 'table' . It turns out, the prawnto plugin only requires prawn in the prawnto/lib/prawnto.rb file. You need to also require 'prawn/console' and 'prawn/layout' Hopefully this will save someone some heartache.
Hi Ryan, thanks for this screencast. One Question: Did someone get it work under rails 3 already? And how? ;-)
So its almost June 2010,.. can prawn/prawnto now finally support merging PDFs together as requested by @powerplant on March 16, 2009? And be in a release of prawn/prawnto which supports prawn-format?
@71. Regnum
Thanks for the file renaming tip. Also I found that you can't have spaces in the name of your file or it cuts off everything after the first space. I just replaced them with underscores thru a helper method.
Hi,
good job as always Ryan.
Anyway i found a problem using prawn: i made a table and i cannot manage to have bold text inside the table.
i tried putting a cell and it works in some ways, but i need single words to be formatted separately.
is there any way to do that?
thanks in advance
hi Ryan
can u please tell me how to use prawn with UTF-8 support.
simple. now there is a gem for prawnto plugin. install it as always.
1. gem install prawn #this will install prawn 0.8.4 -core, -layout, -security
2. gem install prawnto #this will install prawnto 0.0.1
3. in environment.rb file write dependency to this gems:
config.gem "prawn"
config.gem "prawnto"
4. in the controller action you must specify format.pdf in respond_to method. ie. controller action is show as railcast. you must put something like.
def show
@order = Order.find(params[:id])
respond_to do |format|
format.html
format.pdf {:render => false }
end
end
5. Create your view as shown in railcast. name_of_action_view.pdf.prawn
I hope it helps someone.
prawn 0.8.4 has a bug for which images will overflow to the next pages.
They have submitted a fix but instructions on how to get the new changes are vague (yes, i tried to even git clone the repository and that broke my other Prawn stuff which were working fine).
Prolly need to do another video, Ryan? :)
thank you
Chris C wrote:"Hopefully this will save someone some heartache."
Sure cured it though, let me tell you.
I was doing apt-get install libprawn, but needed gem install prawn, nearly drove me out of my mind!!@#$%^
You da man!
Hi Ryan,
Is there a way to display different colours for text in tables.
EG. I have a table with some fields and due date field.
I want to display the text in red if due_date > Date.today and in green colour if due_date < Date.today
Thanks,
Aj
Great screen cast, Ryan!
Came just in time when I needed it! :)
congratulation Ryan for the great screanshot!!!
I'm using prawnto now I feel that I'm in right way!!!
Thanks a lot Ryan for the smooth introduction to Prawn. I just needed a start for pdf creation!
Hi,
I've been using Prawnto / Prawn and followed your railcast (great job btw, been subscribed since day one almost).
I seem to have hit a hurdle which I believe is to do with the recent rails releases (I am using 2.3.8 with ruby 1.8.7.
when adding :format => 'pdf' (:pdf) the url generated is :
localhost:3000/controller/action/id?format=pdf
and not
localhost:3000/controller/action/id.pdf
browsing directly to the id.pdf url works fine but with the link_to command the file that I download is named - unknown - which is not the desired result. it doesn't have a pdf extension even so a rename is needed before i can view it offline.
any thoughts?
thanks,
Liad
For those of you asking for rails layout with prawn. I did it, you'll find my fork of prawnto at github, see: http://github.com/phurni/prawnto
I'v done it for Rails 2.3
Cheers,
Pascal
For those who are interested: I couldn't find a plugin for adding qrcodes to a prawn pdf, so i created one: https://github.com/torandi/prawn-qrcode
Regarding the fix for the undefined method 'table' error, it didn't work at first but I realized that it was 'prawn/core' that needed to be required and not 'prawn/console' as stated above. Just in case someone else is facing this issue. --> using prawnto v0.99, rails 2.1.0 (which is why I have to use an older version of prawnto) :o(
If anybody wants to use prawnto, it's become very out of date. I have tried to merge all the fragmented branches and update the code for rails 3.1. You can find the newest version with instructions and a wiki at https://github.com/forrest/prawnto.
Hope it helps!
How can I send this pdf to various email address. Please please help me.
I get this error "undefined method `table' for #Prawn::Document:0x007fb57e0551a0". Anyone knows what might be going on?