The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Generating PDF Documents with Rails and PDFlib - Part II

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Bob Silva

Posts: 94
Nickname: bobsilva
Registered: Feb, 2006

Bob Silva is a Rails Developer for the UMESD
Generating PDF Documents with Rails and PDFlib - Part II Posted: Apr 22, 2006 7:23 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Bob Silva.
Original Post: Generating PDF Documents with Rails and PDFlib - Part II
Feed Title: Rails Video Tutorials
Feed URL: http://www.railtie.net/xml/rss/feed.xml
Feed Description: A growing collection of screencasts that show you how to use the many facets of the wonderful world of rails.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Bob Silva
Latest Posts From Rails Video Tutorials

Advertisement

Here is Part II of my series on PDF generation from Rails. Part I covered installing and configuring the PDFlib-Lite library from PDFlib.com. In this part, I will walk you through creating this from scratch.


Ready to begin?

First you need to download this zip file which contains a PDFlib wrapper which makes generating PDFs so much easier. It also contains the source code and images used in this tutorial. Extract the zip file and copy the pdf.rb into the lib directory of your Rails application. Then copy the rails.gif image somewhere on your filesystem. Doesn't matter where, we'll tell PDFlib where to find it later.

Open an existing controller or create a new one and addan action named pdftest as shown below:

  def pdftest
    send_data(render_to_string(:action => 'pdftest', :layout => false),
      :filename => "pdftest.pdf", 
      :type => "application/pdf", 
      :disposition => "inline")
  end
This method will render the PDF generated in the rhtml file to a string, and pass it through to the web browser using the send_data method in Rails.


Next, create a new pdftest.rhtml file in the appropriate app/views directory for the controller you just added the pdftest action to.


Lets start coding. Open the pdftest.rhtml in your favorite editor and follow me down the yellow brick road....

<%

# Create the PDF object and reverse the coordinate system. By
# default, PDFs cartesian coordinate system starts with (0,0)
# in the lower left corner. By setting @topdown => true, we flip
# the coordinate system upside to make the upper left (0,0).
# You can also set default margins and page sizes during initialization
p = PDF.new(:topdown => true)

# When working with PDFs, the typical structure is a document 
# with many pages. Calling open begins what PDFlib refers to as
# document scope.
p.open

  # Our PDF only needs one page to display the book cover
  # so we'll open a new page here, and close it at the end
  p.beginpage

    # When working with PDFs, setting a base font/size is required 
    # before writing any text to the page. We wont use this font for
    # this page, but thats OK
    p.font('Helvetica', 10, '#000000')

    # Remember when I said we would tell PDFlib where to find
    # our images? Here ya go. Stick in the path to where you
    # copied rails.gif to.
    p.set_parameter('SearchPath', '/path/to/images')


    # Let the fun begin. We'll start out with the book outline.
    # Just gonna draw a black outline and fill it with white.
    # Using the rect method, this is easy to do. By passing
    # the stroke and fill colors, we tell the method to both
    # stroke and fill the path created.
    # def rect(x, y, w, h, options={})
    p.rect(p.left_margin,
           p.top_margin,
           p.page_width-(p.left_margin+p.right_margin),
           p.page_height-(p.top_margin+p.bottom_margin),
           :fillcolor => '#ffffff',
           :strokecolor => '#000000')
    
    # Next up is the maroon tab at the top of the book with 
    # the text 'The Pragmatic Programmers'. To draw out this
    # odd shape, we'll create a path and pass an multi-dimensional
    # array of points for the path to follow. This time, by only
    # specifiying a fillcolor, we are telling PDFlib not to stroke
    # the path, but only fill it.
    p.path([[102,p.top_margin],
            [312, p.top_margin],
            [300, p.top_margin+63],
            [114, p.top_margin+63]],
            :fillcolor => '#741415')
    
    # Time to add the text in the pretty maroon box we just made.
    # Here, we set the font we want to use ahead of time. Later,
    # I'll show you a different way to do it inline.
    p.font('Times-Roman', 16, '#ffffff')
    p.print 'The', 160, 51
    p.print 'Pragmatic', 151, 66
    p.print 'Programmers', 172, 80
        
    # For the Title of the Book, we demonstrate how we can
    # use pass-through options for native PDFlib functionality
    # not provided for in the wrapper. We are able to adjust
    # the charspacing and horizscaling by passing those options
    # as Hash elements and the wrapper library sends them onto
    # the native PDFlib method. This also demonstrates how
    # to set the font/fontsize inline on a single call to print
    p.font('Times-Roman', 60, '#000000')
    p.print 'Agile', 112, 230 
    p.print 'Web', 254, 230, :charspacing => -2
    p.print 'Development', 162, 278, :horizscaling => 105
    p.print 'with', 248, 308, :fontsize => 38
    p.print 'Rails', 322, 324, :horizscaling => 110
    
    # Working with images in PDFs is easy as you can see below.
    # Pass the name and location and walla, an image in your PDF.
    # Images can be used as templates for forms as well. If you have
    # complex line layouts, its easier to save an image version of the
    # raw template, then insert it as a background layer and write on
    # top of it.
    p.image 'rails.gif', 140, 330
    
    # In these print calls, we give the :boxsize of the textfield 
    # and specify the :position to obtain right aligned text.
    p.font('Courier-BoldOblique', 14)
    p.print 'Dave Thomas', 300, 600, :boxsize => '{205 20}', :position => '{right bottom}'
    p.print 'David Heinemeier Hansson', 300, 618, :boxsize => '{205 20}', :position => '{right bottom}'
    
    # Just another rectangle here for the footer of the cover.
    p.rect(p.left_margin, 
           p.page_height-p.bottom_margin-35,
           p.page_width-p.left_margin-p.right_margin,
           35,
           :fillcolor => '#741415')
    
    # Here we right align the text, set the fillcolor for the font,
    # and set the font/fontsize inline on the print call
    p.print 'The Facets of Ruby Series', 260, 754, :boxsize => '{310 20}', :position => '{right center}', :fillcolor => '#ffffff', :font => 'Times-Roman', :fontsize => 24
    
  p.endpage
p.close

# This next line actually sends the in-memory PDF back to the 
# controller as a string so that it can be sent to the browser.
%>

<%= p.read -%>

If you PDF doesn't look like this, then you didn't follow me very well. As you can see, generating PDF's doesn't have to be difficult, but it can be time consuming as you get into more complex layouts. I'm done with my PDF work on my latest application, so this will conclude this series on Generating PDFs in Rails. Have fun!

Read: Generating PDF Documents with Rails and PDFlib - Part II

Topic: Sleep Previous Topic   Next Topic Topic: Java 5 now default VM on OS X

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use