#153
Mar 16, 2009

PDFs with Prawn

Prawn is an excellent Ruby library for generating PDF documents. Learn how to use it along with the Prawnto plugin in this episode.
Tags: plugins
Download (20 MB, 10:04)
alternative download for iPod & Apple TV (12.4 MB, 10:04)

Resources

sudo gem install prawn
script/plugin install git://github.com/thorny-sun/prawnto.git
# views/orders/show.pdf.prawn
pdf.text "Order ##{@order.id}", :size => 30, :style => :bold

pdf.move_down(30)

items = @order.cart.line_items.map do |item|
  [
    item.product.name,
    item.quantity,
    number_to_currency(item.unit_price),
    number_to_currency(item.full_price)
  ]
end

pdf.table items, :border_style => :grid,
  :row_colors => ["FFFFFF","DDDDDD"],
  :headers => ["Product", "Qty", "Unit Price", "Full Price"],
  :align => { 0 => :left, 1 => :right, 2 => :right, 3 => :right }

pdf.move_down(10)

pdf.text "Total Price: #{number_to_currency(@order.cart.total_price)}", :size => 16, :style => :bold

# orders_controller.rb
prawnto :prawn => { :top_margin => 75 }

def show
  @order = Order.find(params[:id])
end
<p><%= link_to "Printable Invoice (PDF)", order_path(@order, :format => 'pdf') %></p>

RSS Feed for Episode Comments 88 comments

1. Millisami Mar 16, 2009 at 00:08

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


2. Carl Mar 16, 2009 at 01:07

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


3. James Healy Mar 16, 2009 at 01:08

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


4. Igor Mar 16, 2009 at 01:11

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!
;)


5. Mephux Mar 16, 2009 at 01:53

**NOTE:
You also will need format.pdf in the controller.. just thought I would add that.


6. Alexei Mar 16, 2009 at 03:54

@Mephux
Ryan told that it's not required.


7. Gregory Brown Mar 16, 2009 at 05:32

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


8. Daniel Lopes Mar 16, 2009 at 05:59

Anyone know some good tool for read(parse) pdf files?

Thanks for another great video Ryan!


9. mephux Mar 16, 2009 at 06:49

@Alexei
Was for me on 2.3.1.. hhmm wonder what the issue was then.


10. Powerplant Mar 16, 2009 at 06:51

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


11. Gregory Mar 16, 2009 at 07:32

@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/


12. Ryan Bates Mar 16, 2009 at 08:08

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


13. gUI Mar 16, 2009 at 09:07

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.


14. Eric Mar 16, 2009 at 09:19

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. :)


15. Rajesh Rajappan Mar 16, 2009 at 11:55

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.


16. Mark Mar 16, 2009 at 12:29

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


17. Rajesh Rajappan Mar 16, 2009 at 12:57

Hi Mark, Thanks. I was using the make_resourceful plugin and didn't think i needed the format.pdf option.

Thanks for your help


18. Mourad Mar 16, 2009 at 14:11

Thank you Ryan for all the screen casts :)


19. Dinshaw Mar 16, 2009 at 15:36

I second the thanks. Your screen casts are the coolest way to learn.


20. Will Mar 16, 2009 at 16:19

Thanks! I've got to say I really like the plugin screencasts, like this one, a lot more than the new rails features ones!


21. Alexander Mar 17, 2009 at 01:25

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)


22. George Yacoub Mar 17, 2009 at 03:58

Thanks Ryan.


23. Jean-Marc Mar 17, 2009 at 07:50

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?


24. Kaspars Bankovskis Mar 17, 2009 at 14:51

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


25. Vishal Sankhla Mar 17, 2009 at 15:46

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.


26. Gregory Brown Mar 17, 2009 at 19:22

@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/


27. jhc_ Mar 18, 2009 at 09:42

@Alexander

About ./script/plugin not working :
http://rails.lighthouseapp.com/projects/8994/tickets/2018-ruby-19-compat-plugininstall-git-always-fails-in-ruby-19


28. Chuck Bergeron Mar 18, 2009 at 10:23

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!


29. Alexander Mar 18, 2009 at 13:48

@jhc_
Thank you! It works for me


30. Thiago Mar 18, 2009 at 15:13

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.


31. Gregory Brown Mar 18, 2009 at 21:37

@Thiago:

What specifically is rghost nicer for? I asked for feedback on what we should steal from it a while ago :)


32. Stefan Mar 19, 2009 at 10:04

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?


33. Tilo S Mar 20, 2009 at 01:26

Great screen cast, Ryan!
Came just in time when I needed it! :)


34. Thiago Mar 20, 2009 at 04:31

@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)


35. Gregory Brown Mar 21, 2009 at 22:02

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


36. Richard Mar 24, 2009 at 14:00

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


37. Vinay Mar 24, 2009 at 22:59

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.


38. Vinay Mar 24, 2009 at 23:39

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?


39. Ryan Tyler Mar 27, 2009 at 09:17

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


40. Karant Apr 04, 2009 at 20:33

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.


41. Oleg Bovykin Apr 07, 2009 at 14:31

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?


42. Samo Apr 08, 2009 at 09:53

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!


43. Jeremy Apr 10, 2009 at 03:32

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


44. Bob Apr 10, 2009 at 08:24

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


45. Samo Apr 10, 2009 at 10:16

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


46. Owen Madden Apr 11, 2009 at 08:30

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


47. Chui Apr 11, 2009 at 15:46

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?


48. Hubert Łępicki Apr 15, 2009 at 05:17

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


49. Johannes Apr 15, 2009 at 14:20

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)


50. Tim Apr 17, 2009 at 03:00

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?


51. Steve Apr 17, 2009 at 14:15

Thanks Ryan. This cast did a great job at helping to jumpstart my usage of Prawn. It's a very useful library.


52. Kris Apr 21, 2009 at 08:43

Anyone know why my request to join the prawn Google group was not approved?


53. Jim Alateras Apr 24, 2009 at 07:02

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


54. Ryan Tyler Apr 27, 2009 at 08:57

Johannes:

I have it working fine in latest version.


55. Johannes Apr 30, 2009 at 08:42

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 ... ;)


56. Thijs de Vries May 01, 2009 at 10:07

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.


57. Renjith May 08, 2009 at 04:16

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


58. Espen May 16, 2009 at 11:41

I got the same error as Alexander.. Had a look at the patch, but don't know how to implement it. Help anyone?


59. Ryan H May 20, 2009 at 23:08

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


60. Sami May 26, 2009 at 00:07

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). :-(


61. Bryan Jun 01, 2009 at 06:21

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 ?


62. Mike Jun 01, 2009 at 15:48

bryan, try adding "format.pdf" in your respond_to block.


63. Patric Caramachi Jun 02, 2009 at 06:01

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 :)


64. CB Jun 02, 2009 at 13:04

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?


65. Jim Jun 06, 2009 at 17:03

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' )


66. Samo Jun 17, 2009 at 14:03

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 :)


67. Deb Prado Jun 22, 2009 at 10:06

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


68. BarnaB Jun 23, 2009 at 15:43

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 }


69. sijo Jun 29, 2009 at 22:30

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 }


70. pravin Jul 09, 2009 at 23:05

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


71. Revgum Jul 21, 2009 at 12:41

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'"


72. Shooni Jul 29, 2009 at 00:51

Hi guys,

Could anybody please tell me how to use bullets with my text?

Thanks


73. Avrohom Katz Aug 15, 2009 at 12:12

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.


74. jaz Aug 24, 2009 at 06:42

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.


75. sravanthi Aug 24, 2009 at 22:42

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


76. sravanthi Aug 25, 2009 at 06:13

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


77. jaz Aug 25, 2009 at 06:47

Is it possible to set one of the columns in the table to use a different type of font than the rest?


78. Hagen Volpers Sep 23, 2009 at 03:44

@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


79. Bohdan Oct 23, 2009 at 01:53

is there any way to make footers work when printing multi-page table?


80. Filipe Grillo Dec 30, 2009 at 07:22

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


81. merchant solutions llc Jan 10, 2010 at 22:15

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.


82. swivel Feb 01, 2010 at 01:16

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)


83. Bijan Feb 03, 2010 at 04:24

THX for this gr8 tutorial Ryan!
Q: How can I set the table headers bold with the inline prawnto?


84. Sandra Feb 03, 2010 at 08:42

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


85. Sandra Feb 04, 2010 at 01:16

I found a solution:

prawnto :filename => 'filename.pdf'

Thx, Sandra


86. omar Feb 07, 2010 at 18:44

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


87. Louis Vuitton handbags Mar 09, 2010 at 18:50

railscasts.com/episodes/153-pdfs-with-prawn


88. Mark D Mar 10, 2010 at 05:15

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

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source