`

How To Generate PDFs in Rails With Prawn

阅读更多

How To Generate PDFs in Rails With Prawn

It’s been a while since I’ve needed to generate a PDF in ruby. I typically discourage clients from it because, well, I’m lazy and it’s a pain. I’ve always kind of hated pdf generation. It has always felt a tad awkward, be it in PHP, ColdFusion (6, unfortunately before cfdocument) and even Ruby. This time around, I decided to try out the new kid on the block, Prawn. On the website I just linked to, they recommend the prawnto plugin, so I gave it a whirl. My conclusions are that they work pretty well. Granted, I was just creating some text and formatting it, but I got up and running quickly. For your enjoyment, I’ll cover some basics below.
Create and Install

Note: I’m assuming Rails 2.1+. Fire up terminal and create a new app and install the prawnto plugin.

rails prawn_demo
sudo gem install prawn
script/plugin install git://github.com/thorny-sun/prawnto.git


Now add prawn as a dependency in environment.rb.

config.gem 'prawn'

For the sake of the demo we’ll need some demo data. Let’s create a Book model with some columns that we can shove lorem ipsum into.

script/generate scaffold book title:string author:string description:text
rake db:migrate

BooksController#show Example

I ran over to The Pragmatic Programmer’s site and snagged a few titles to enter as test data. 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 { render :layout => false } so that the action looks something like this:

def show
  @book = Book.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.xml  { renderml => @book }
    format.pdf { render :layout => false }
  end
end


Now if you visit http://localhost:3000/books/2.pdf, you’ll get a template is missing error. Let’s add the show view. The prawnto plugin adds all the wiring, so all you need to do is create the show.pdf.prawn file inside app/views/books. For now, lets hello world that mofo with the following:

pdf.text "Hello World!"

Now if you revisit that url, you’ll get a pdf that says hello world. Simple, eh? Let’s make the view specific to the book and tweak the look a bit.

pdf.font "Helvetica"
pdf.font.size = 13
pdf.text "Book: #{@book.title}", :size => 16, :style => :bold, :spacing => 4
pdf.text "Author: #{@book.author}", :spacing => 16
pdf.text @book.description


The first two lines set the default font stuff. As you can see, pdf.text takes a string and then a hash of options. :size adjust the font size, :style changes the weight, and :spacing controls the space between lines. Pretty self-explanatory, but I thought I would cover it anyway.
BooksController#index Example

Now let’s create a pdf of all the books with each book on it’s own page. Add format.pdf { render :layout => false } to the respond to block in the index action and create the following index.pdf.prawn view:

pdf.font "Helvetica"
pdf.font.size = 13

@books.each do |book|
  pdf.text "Book: #{book.title}", :size => 16, :style => :bold, :spacing => 4
  pdf.text "Author: #{book.author}", :spacing => 16
  pdf.text book.description
  pdf.start_new_page
end


So the examples I showed were pretty basic and there is a lot more you can do with prawn, but I didn’t feel like coming up with examples. Helpers work just like in views which is handy. Also, prawn does images and data tables in a pretty simple manner. Check out the prawn and prawnto websites for more.
Posted by jnunemaker in Gems, Plugins
分享到:
评论

相关推荐

    How to generate ns2 trace files with VanetMobiSim

    介绍如何在VanetMobiSim中产生NS2能够使用的trace file

    How to use SFTP

    You should ensure that the server's public keys are loaded by the client as described in How to use SFTP (with server validation - known hosts), or you may want to switch off server validation to get ...

    How to generate the complex data regularly by DB Query Analyzer

    Considering the complex of the data required by Ministry of Transport of P.R.C every period of ten days, I design the following algorithm to generate the data required.

    RJS Templates for Rails

    RJS templates are an exciting and powerful new type ... This document helps you get acquainted with how RJS templates fit into the Rails framework and gets you started with a few easy-to-follow examples.

    How is logging implemented in OSS?

    To generate logs, logging practice is accepted by developers to place logging statements in the source code of software systems. Compared to the great number of studies on log analysis, the research ...

    matplotlib Plotting Cookbook: Learn how to create professional scientific plots

    You can generate plots, add dimensions to the plots, and also make the plots interactive with just a few lines of code with matplotlib. Also, matplotlib integrates well with all common GUI modules. ...

    prawn_rails_demo:prawn_rails 插件的演示

    Prawn Rails是一个Ruby库,它将Prawn PDF生成器与Ruby on Rails框架集成,使得在Rails应用中创建和处理PDF文档变得更加便捷。本项目"prawn_rails_demo"是一个示例,展示了如何在Rails应用程序中有效地使用Prawn ...

    WPF Data Binding with LINQ to SQL

    Even if you do choose to auto-generate your classes, understanding how these techniques work will allow you to expand the code to better fit your application's needs and to better troubleshoot issues...

    Code.Generation.with.Roslyn.epub

    Code Generation with Rosyln is the first book to cover this new capability. You will learn how these techniques can be used to simplify systems integration so that if one system already defines ...

    iTextSharp in Action

    The .NET framework does not contain any native way to work with PDF files.... So, as part of a series of How To articles, here's how to get started using iTextSharp with code samples in C#.

    Machine Learning Projects with TensorFlow 2.0:Supercharge your Machine Learning

    Natural Language Processing Task – How to Generate Our Own Text 18 Introduction to Natural Language Processing 19 NLP and the Importance of Data Preprocessing 20 A Simple Text Classifier 21 Text ...

    Sudoku.Programming.with.C.1484209966

    Sudoku Programming with C teaches you how to write computer programs to solve and generate Sudoku puzzles. This is a practical book that will provide you with everything you need to write your own ...

    Thinking in LINQ

    how to generate recursive patterns and mathematical series. • Chapter 3: Text Processing Text processing is a blanket term used to cover a range of tasks, from generation of text to spell-checking. ...

Global site tag (gtag.js) - Google Analytics