The Prawn::Document class is how you start creating a PDF document.

There are three basic ways you can instantiate PDF Documents in Prawn, they are through assignment, implicit block or explicit block. Below is an exmple of each type, each example does exactly the same thing, makes a PDF document with all the defaults and puts in the default font “Hello There” and then saves it to the current directory as “example.pdf“

For example, assignment can be like this:

  pdf =
  pdf.text "Hello There"
  pdf.render_file "example.pdf"

Or you can do an implied block form:

  Prawn::Document.generate "example.pdf" do
    text "Hello There"

Or if you need to access a variable outside the scope of the block, the explicit block form:

  words = "Hello There"
  Prawn::Document.generate "example.pdf" do |pdf|
    pdf.text words

Usually, the block forms are used when you are simply creating a PDF document that you want to immediately save or render out.

See the new and generate methods for further details on the above.



Public Class Methods

extensions() click to toggle source

Any module added to this array will be included into instances of Prawn::Document at the per-object level. These will also be inherited by any subclasses.


  module MyFancyModule

    def party!
      text "It's a big party!"


  Prawn::Document.extensions << MyFancyModule

  Prawn::Document.generate("foo.pdf") do
    # File lib/prawn/document.rb, line 85
85:     def self.extensions
86:       @extensions ||= []
87:     end
generate(filename,options={},&block) click to toggle source

Creates and renders a PDF document.

When using the implicit block form, Prawn will evaluate the block within an instance of Prawn::Document, simplifying your syntax. However, please note that you will not be able to reference variables from the enclosing scope within this block.

  # Using implicit block form and rendering to a file
  Prawn::Document.generate "example.pdf" do
    # self here is set to the newly instantiated Prawn::Document
    # and so any variables in the outside scope are unavailable
    font "Times-Roman"
    draw_text "Hello World", :at => [200,720], :size => 32

If you need to access your local and instance variables, use the explicit block form shown below. In this case, Prawn yields an instance of PDF::Document and the block is an ordinary closure:

  # Using explicit block form and rendering to a file
  content = "Hello World"
  Prawn::Document.generate "example.pdf" do |pdf|
    # self here is left alone
    pdf.font "Times-Roman"
    pdf.draw_text content, :at => [200,720], :size => 32
     # File lib/prawn/document.rb, line 120
120:     def self.generate(filename,options={},&block)
121:       pdf = new(options,&block)
122:       pdf.render_file(filename)
123:     end
new(options={},&block) click to toggle source

Creates a new PDF Document. The following options are available (with the default values marked in [])


One of the Document::PageGeometry sizes [LETTER]


Either :portrait or :landscape


Sets the margin on all sides in points [0.5 inch]


Sets the left margin in points [0.5 inch]


Sets the right margin in points [0.5 inch]


Sets the top margin in points [0.5 inch]


Sets the bottom margin in points [0.5 inch]


Creates a document without starting the first page [false]


Compresses content streams before rendering them [false]


Reduce number of PDF objects in output, at expense of render time [false]


An image path to be used as background on all pages [nil]


Generic hash allowing for custom metadata properties [nil]


The path to an existing PDF file to use as a template [nil]

Setting e.g. the :margin to 100 points and the :left_margin to 50 will result in margins of 100 points on every side except for the left, where it will be 50.

The :margin can also be an array much like CSS shorthand:

  # Top and bottom are 20, left and right are 100.
  :margin => [20, 100]
  # Top is 50, left and right are 100, bottom is 20.
  :margin => [50, 100, 20]
  # Top is 10, right is 20, bottom is 30, left is 40.
  :margin => [10, 20, 30, 40]

Additionally, :page_size can be specified as a simple two value array giving the width and height of the document you need in PDF Points.


  # New document, US Letter paper, portrait orientation
  pdf =

  # New document, A4 paper, landscaped
  pdf = => "A4", :page_layout => :landscape)

  # New document, Custom size
  pdf = => [200, 300])

  # New document, with background
  pdf = => "#{Prawn::BASEDIR}/data/images/pigs.jpg")
     # File lib/prawn/document.rb, line 171
171:     def initialize(options={},&block)
172:        Prawn.verify_options [:page_size, :page_layout, :margin, :left_margin,
173:          :right_margin, :top_margin, :bottom_margin, :skip_page_creation,
174:          :compress, :skip_encoding, :background, :info,
175:          :optimize_objects, :template], options
177:        # need to fix, as the refactoring breaks this
178:        # raise NotImplementedError if options[:skip_page_creation]
180:        self.class.extensions.reverse_each { |e| extend e }
181:        @internal_state =
182:        @internal_state.populate_pages_from_store(self)
183:        min_version( if
185:        @background = options[:background]
186:        @font_size  = 12
188:        @bounding_box  = nil
189:        @margin_box    = nil
191:        @page_number = 0
193:        options[:size] = options.delete(:page_size)
194:        options[:layout] = options.delete(:page_layout)
196:        if options[:template]
197:          fresh_content_streams(options)
198:          go_to_page(1)
199:        else
200:          if options[:skip_page_creation] || options[:template]
201:            start_new_page(options.merge(:orphan => true))
202:          else
203:            start_new_page(options)
204:          end
205:        end
207:        @bounding_box = @margin_box
209:        if block
210:          block.arity < 1 ? instance_eval(&block) : block[self]
211:        end
212:      end

Public Instance Methods

bounding_box(point, options={}, &block) click to toggle source

A bounding box serves two important purposes:

  • Provide bounds for flowing text, starting at a given point

  • Translate the origin (0,0) for graphics primitives

A point and :width must be provided. :height is optional. (See stretchyness below)


Bounding boxes are positioned relative to their top left corner and the width measurement is towards the right and height measurement is downwards.


  • Bounding box 100pt x 100pt in the absolute bottom left of the containing box:

    pdf.bounding_box([0,100], :width => 100, :height => 100)



  • Bounding box 200pt x 400pt high in the center of the page:

    x_pos = ((bounds.width / 2) - 150) y_pos = ((bounds.height / 2) + 200) pdf.bounding_box([x_pos, y_pos], :width => 300, :height => 400) do



Flowing Text

When flowing text, the usage of a bounding box is simple. Text will begin at the point specified, flowing the width of the bounding box. After the block exits, the cursor position will be moved to the bottom of the bounding box (y - height). If flowing text exceeds the height of the bounding box, the text will be continued on the next page, starting again at the top-left corner of the bounding box.


  pdf.bounding_box([100,500], :width => 100, :height => 300) do
    pdf.text "This text will flow in a very narrow box starting" +
     "from [100,500]. The pointer will then be moved to [100,200]" +
     "and return to the margin_box"

Note, this is a low level tool and is designed primarily for building other abstractions. If you just need to flow text on the page, you will want to look at span() and text_box() instead

Translating Coordinates

When translating coordinates, the idea is to allow the user to draw relative to the origin, and then translate their drawing to a specified area of the document, rather than adjust all their drawing coordinates to match this new region.

Take for example two triangles which share one point, drawn from the origin:

  pdf.polygon [0,250], [0,0], [150,100]
  pdf.polygon [100,0], [150,100], [200,0]

It would be easy enough to translate these triangles to another point, e.g [200,200]

  pdf.polygon [200,450], [200,200], [350,300]
  pdf.polygon [300,200], [350,300], [400,200]

However, each time you want to move the drawing, you’d need to alter every point in the drawing calls, which as you might imagine, can become tedious.

If instead, we think of the drawing as being bounded by a box, we can see that the image is 200 points wide by 250 points tall.

To translate it to a new origin, we simply select a point at (x,y+height)

Using the [200,200] example:

  pdf.bounding_box([200,450], :width => 200, :height => 250) do
    pdf.stroke do
      pdf.polygon [0,250], [0,0], [150,100]
      pdf.polygon [100,0], [150,100], [200,0]

Notice that the drawing is still relative to the origin. If we want to move this drawing around the document, we simply need to recalculate the top-left corner of the rectangular bounding-box, and all of our graphics calls remain unmodified.

Nesting Bounding Boxes

At the top level, bounding boxes are specified relative to the document’s margin_box (which is itself a bounding box). You can also nest bounding boxes, allowing you to build components which are relative to each other


 pdf.bounding_box([200,450], :width => 200, :height => 250) do
   pdf.stroke_bounds   # Show the containing bounding box
   pdf.bounding_box([50,200], :width => 50, :height => 50) do
     # a 50x50 bounding box that starts 50 pixels left and 50 pixels down
     # the parent bounding box.


If you do not specify a height to a bounding box, it will become stretchy and its height will be calculated automatically as you stretch the box downwards.

 pdf.bounding_box([100,400], :width => 400) do
   pdf.text("The height of this box is #{pdf.bounds.height}")
   pdf.text('this is some text')
   pdf.text('this is some more text')
   pdf.text('and finally a bit more')
   pdf.text("Now the height of this box is #{pdf.bounds.height}")

Absolute Positioning

If you wish to position the bounding boxes at absolute coordinates rather than relative to the margins or other bounding boxes, you can use canvas()

 pdf.bounding_box([50,500], :width => 200, :height => 300) do
   pdf.canvas do
     Positioned outside the containing box at the 'real' (300,450)
     pdf.bounding_box([300,450], :width => 200, :height => 200) do

Of course, if you use canvas, you will be responsible for ensuring that you remain within the printable area of your document.

     # File lib/prawn/document/bounding_box.rb, line 157
157:     def bounding_box(*args, &block)
158:       init_bounding_box(block) do |parent_box|
159:         map_to_absolute!(args[0])
160:         @bounding_box =, parent_box, *args)
161:       end
162:     end
bounds() click to toggle source

The bounds method returns the current bounding box you are currently in, which is by default the box represented by the margin box on the document itself. When called from within a created bounding_box block, the box defined by that call will be returned instead of the document margin box.

Another important point about bounding boxes is that all x and y measurements within a bounding box code block are relative to the bottom left corner of the bounding box.

For example: do
   # In the default "margin box" of a Prawn document of 0.5in along each edge

   # Draw a border around the page (the manual way)
   stroke do
     line(bounds.bottom_left, bounds.bottom_right)
     line(bounds.bottom_right, bounds.top_right)
     line(bounds.top_right, bounds.top_left)
     line(bounds.top_left, bounds.bottom_left)

   # Draw a border around the page (the easy way)
     # File lib/prawn/document.rb, line 387
387:     def bounds
388:       @bounding_box
389:     end
bounds=(bounding_box) click to toggle source

Sets Document#bounds to the BoundingBox provided. See above for a brief description of what a bounding box is. This function is useful if you really need to change the bounding box manually, but usually, just entering and exiting bounding box code blocks is good enough.

     # File lib/prawn/document.rb, line 396
396:     def bounds=(bounding_box)
397:       @bounding_box = bounding_box
398:     end
canvas(&block) click to toggle source

A shortcut to produce a bounding box which is mapped to the document’s absolute coordinates, regardless of how things are nested or margin sizes.

  pdf.canvas do
    pdf.line pdf.bounds.bottom_left, pdf.bounds.top_right
     # File lib/prawn/document/bounding_box.rb, line 171
171:     def canvas(&block)
172:       init_bounding_box(block, :hold_position => true) do |_|
173:         # Canvas bbox acts like margin_box in that its parent bounds are unset.
174:         @bounding_box =, nil, [0,page.dimensions[3]],
175:           :width => page.dimensions[2],
176:           :height => page.dimensions[3]
177:         )
178:       end
179:     end
cell(options={}) click to toggle source

Instantiates and draws a cell on the document.

  cell(:content => "Hello world!", :at => [12, 34])

See Prawn::Table::Cell.make for full options.

    # File lib/prawn/table/cell.rb, line 18
18:     def cell(options={})
19:       cell = Table::Cell.make(self, options.delete(:content), options)
20:       cell.draw
21:       cell
22:     end
column_box(*args, &block) click to toggle source

A column box is a bounding box with the additional property that when text flows past the bottom, it will wrap first to another column on the same page, and only flow to the next page when all the columns are filled.

column_box accepts the same parameters as bounding_box, as well as the number of :columns and a :spacer (in points) between columns.

Defaults are :columns = 3 and :spacer = font_size

Under PDF::Writer, “spacer” was known as “gutter“

    # File lib/prawn/document/column_box.rb, line 23
23:     def column_box(*args, &block)
24:       init_column_box(block) do |parent_box|
25:         map_to_absolute!(args[0])
26:         @bounding_box =, parent_box, *args)
27:       end
28:     end
compression_enabled?() click to toggle source

Returns true if content streams will be compressed before rendering, false otherwise

     # File lib/prawn/document.rb, line 610
610:     def compression_enabled?
611:       !!state.compress
612:     end
cursor() click to toggle source

The current y drawing position relative to the innermost bounding box, or to the page margins at the top level.

     # File lib/prawn/document.rb, line 311
311:     def cursor
312:       y - bounds.absolute_bottom
313:     end
define_grid(options = {}) click to toggle source

Defines the grid system for a particular document. Takes the number of rows and columns and the width to use for the gutter as the keys :rows, :columns, :gutter, :row_gutter, :column_gutter

    # File lib/prawn/layout/grid.rb, line 8
 8:     def define_grid(options = {})
 9:       @grid =, options)
10:     end
float() click to toggle source

Executes a block and then restores the original y position

  pdf.text "A"

  pdf.float do
    pdf.move_down 100
    pdf.text "C"

  pdf.text "B"
     # File lib/prawn/document.rb, line 332
332:     def float
333:       mask(:y) { yield }
334:     end
font(name=nil, options={}) click to toggle source

Without arguments, this returns the currently selected font. Otherwise, it sets the current font. When a block is used, the font is applied transactionally and is rolled back when the block exits.

  Prawn::Document.generate("font.pdf") do
    text "Default font is Helvetica"

    font "Times-Roman"
    text "Now using Times-Roman"

    font("Chalkboard.ttf") do
      text "Using TTF font from file Chalkboard.ttf"
      font "Courier", :style => :bold
      text "You see this in bold Courier"

    text "Times-Roman, again"

The :name parameter must be a string. It can be one of the 14 built-in fonts supported by PDF, or the location of a TTF file. The Font::AFM::BUILT_INS array specifies the valid built in font values.

If a ttf font is specified, the glyphs necessary to render your document will be embedded in the rendered PDF. This should be your preferred option in most cases. It will increase the size of the resulting file, but also make it more portable.

The options parameter is an optional hash providing size and style. To use the :style option you need to map those font styles to their respective font files. See font_families for more information.

    # File lib/prawn/font.rb, line 48
48:     def font(name=nil, options={})
49:       return((defined?(@font) && @font) || font("Helvetica")) if name.nil?
51:       if state.pages.empty? && !
52:         raise Prawn::Errors::NotOnPage 
53:       end
55:       new_font = find_font(name, options)
57:       if block_given?
58:         save_font do
59:           set_font(new_font, options[:size])
60:           yield
61:         end
62:       else
63:         set_font(new_font, options[:size])
64:       end
66:       @font
67:     end
font_families() click to toggle source

Hash that maps font family names to their styled individual font names.

To add support for another font family, append to this hash, e.g:

   "MyTrueTypeFamily" => { :bold        => "foo-bold.ttf",
                           :italic      => "foo-italic.ttf",
                           :bold_italic => "foo-bold-italic.ttf",
                           :normal      => "foo.ttf" })

This will then allow you to use the fonts like so:

  pdf.font("MyTrueTypeFamily", :style => :bold)
  pdf.text "Some bold text"
  pdf.text "Some normal text"

This assumes that you have appropriate TTF fonts for each style you wish to support.

By default the styles :bold, :italic, :bold_italic, and :normal are defined for fonts “Courier”, “Times-Roman” and “Helvetica”.

You probably want to provide those four styles, but are free to define custom ones, like :thin, and use them in font calls.

     # File lib/prawn/font.rb, line 181
181:     def font_families
182:       @font_families ||= { |h,k| h[k] = {} }.merge!(
183:         { "Courier"     => { :bold        => "Courier-Bold",
184:                              :italic      => "Courier-Oblique",
185:                              :bold_italic => "Courier-BoldOblique",
186:                              :normal      => "Courier" },
188:           "Times-Roman" => { :bold         => "Times-Bold",
189:                              :italic       => "Times-Italic",
190:                              :bold_italic  => "Times-BoldItalic",
191:                              :normal       => "Times-Roman" },
193:           "Helvetica"   => { :bold         => "Helvetica-Bold",
194:                              :italic       => "Helvetica-Oblique",
195:                              :bold_italic  => "Helvetica-BoldOblique",
196:                              :normal       => "Helvetica" }
197:         })
198:     end
font_size(points=nil) click to toggle source

When called with no argument, returns the current font size. When called with a single argument but no block, sets the current font size. When a block is used, the font size is applied transactionally and is rolled back when the block exits. You may still change the font size within a transactional block for individual text segments, or nested calls to font_size.

  Prawn::Document.generate("font_size.pdf") do
    font_size 16
    text "At size 16"

    font_size(10) do
      text "At size 10"
      text "At size 6", :size => 6
      text "At size 10"

    text "At size 16"

When called without an argument, this method returns the current font size.

    # File lib/prawn/font.rb, line 92
92:     def font_size(points=nil)
93:       return @font_size unless points
94:       size_before_yield = @font_size
95:       @font_size = points
96:       block_given? ? yield : return
97:       @font_size = size_before_yield
98:     end
go_to_page(k) click to toggle source

Re-opens the page with the given (1-based) page number so that you can draw on it.

See Prawn::Document#number_pages for a sample usage of this capability.

     # File lib/prawn/document.rb, line 296
296:     def go_to_page(k)
297:       @page_number = k
298: = state.pages[k-1]
299:       generate_margin_box
300:       @y = @bounding_box.absolute_top
301:     end
grid(*args) click to toggle source

A method that can either be used to access a particular grid on the page or work with the grid system directly.

  @pdf.grid                 # Get the Grid directly
  @pdf.grid([0,1])          # Get the box at [0,1]
  @pdf.grid([0,1], [1,2])   # Get a multi-box spanning from [0,1] to [1,2]
    # File lib/prawn/layout/grid.rb, line 19
19:     def grid(*args)
20:       @boxes ||= {}
21:       @boxes[args] ||= if args.empty?
22:         @grid
23:       else
24:         g1, g2 = args
25:         if(g1.class == Array && g2.class == Array && 
26:           g1.length == 2 && g2.length == 2)
27:           multi_box(single_box(*g1), single_box(*g2))
28:         else
29:           single_box(g1, g2)
30:         end
31:       end
32:     end
group(second_attempt=false) click to toggle source

Attempts to group the given block vertically within the current context. First attempts to render it in the current position on the current page. If that attempt overflows, it is tried anew after starting a new context (page or column). Returns a logically true value if the content fits in one page/column, false if a new page or column was needed.

Raises CannotGroup if the provided content is too large to fit alone in the current page or column.

     # File lib/prawn/document.rb, line 492
492:     def group(second_attempt=false)
493:       old_bounding_box = @bounding_box
494:       @bounding_box =
496:       def @bounding_box.move_past_bottom
497:         raise RollbackTransaction
498:       end
500:       success = transaction { yield }
502:       @bounding_box = old_bounding_box
504:       unless success
505:         raise Prawn::Errors::CannotGroup if second_attempt
506:         old_bounding_box.move_past_bottom
507:         group(second_attempt=true) { yield }
508:       end
510:       success
511:     end
indent(left, right = 0, &block) click to toggle source

Indents the specified number of PDF points for the duration of the block

 pdf.text "some text"
 pdf.indent(20) do
   pdf.text "This is indented 20 points"
 pdf.text "This starts 20 points left of the above line " +
          "and is flush with the first line"
 pdf.indent 20, 20 do
   pdf.text "This line is indented on both sides."
     # File lib/prawn/document.rb, line 468
468:     def indent(left, right = 0, &block)
469:       bounds.indent(left, right, &block)
470:     end
make_cell(content, options={}) click to toggle source

Set up, but do not draw, a cell. Useful for creating cells with formatting options to be inserted into a Table. Call draw on the resulting Cell to ink it.

See the documentation on Prawn::Cell for details on the arguments.

    # File lib/prawn/table/cell.rb, line 30
30:     def make_cell(content, options={})
31:       Prawn::Table::Cell.make(self, content, options)
32:     end
make_table(data, options={}, &block) click to toggle source

Set up, but do not draw, a table. Useful for creating subtables to be inserted into another Table. Call draw on the resulting Table to ink it.

See the documentation on Prawn::Table for details on the arguments.

    # File lib/prawn/table.rb, line 35
35:     def make_table(data, options={}, &block)
36:, self, options, &block)
37:     end
move_cursor_to(new_y) click to toggle source

Moves to the specified y position in relative terms to the bottom margin.

     # File lib/prawn/document.rb, line 317
317:     def move_cursor_to(new_y)
318:       self.y = new_y + bounds.absolute_bottom
319:     end
move_down(n) click to toggle source

Moves down the document by n points relative to the current position inside the current bounding box.

     # File lib/prawn/document.rb, line 410
410:     def move_down(n)
411:       self.y -= n
412:     end
move_up(n) click to toggle source

Moves up the document by n points relative to the current position inside the current bounding box.

     # File lib/prawn/document.rb, line 403
403:     def move_up(n)
404:       self.y += n
405:     end
number_pages(string, options={}) click to toggle source

Places a text box on specified pages for page numbering. This should be called towards the end of document creation, after all your content is already in place. In your template string, refers to the current page, and refers to the total amount of pages in the document. Page numbering should occur at the end of your Prawn::Document.generate block because the method iterates through existing pages after they are created.

Parameters are:


Template string for page number wording. Should include ’’ and, optionally, ’’.


A hash for page numbering and text box options.

    <tt>:page_filter</tt>:: A filter to specify which pages to place page numbers on.  
                            Refer to the method 'page_match?'
    <tt>:start_count_at</tt>:: The starting count to increment pages from.
    <tt>:total_pages</tt>:: If provided, will replace <total> with the value given.
                            Useful to override the total number of pages when using 
                            the start_count_at option.
    <tt>:color</tt>:: Text fill color.

    Please refer to Prawn::Text::text_box for additional options concerning text
    formatting and placement.

Example: Print page numbers on every page except for the first. Start counting from


  Prawn::Document.generate("page_with_numbering.pdf") do
    number_pages "<page> in a total of <total>", 
                                         {:start_count_at => 5,
                                          :page_filter => lambda{ |pg| pg != 1 },
                                          :at => [bounds.right - 50, 0],
                                          :align => :right,
                                          :size => 14}
     # File lib/prawn/document.rb, line 548
548:     def number_pages(string, options={})
549:       opts = options.dup
550:       start_count_at = opts.delete(:start_count_at).to_i
551:       page_filter = opts.delete(:page_filter)
552:       total_pages = opts.delete(:total_pages)
553:       txtcolor = opts.delete(:color)
554:       # An explicit height so that we can draw page numbers in the margins
555:       opts[:height] = 50
557:       start_count = false
558:       pseudopage = 0
559:       (1..page_count).each do |p|
560:         unless start_count
561:           pseudopage = case start_count_at
562:                        when 0
563:                          1
564:                        else
565:                          start_count_at.to_i
566:                        end
567:         end        
568:         if page_match?(page_filter, p)
569:           go_to_page(p)
570:           # have to use fill_color here otherwise text reverts back to default fill color
571:           fill_color txtcolor unless txtcolor.nil?
572:           total_pages = total_pages.nil? ? page_count : total_pages
573:           str = string.gsub("<page>","#{pseudopage}").gsub("<total>","#{total_pages}")
574:           text_box str, opts
575:           start_count = true  # increment page count as soon as first match found
576:         end 
577:         pseudopage += 1 if start_count
578:       end
579:     end
outline() click to toggle source

Lazily instantiates an Outline object for document. This is used as point of entry to methods to build the outline tree.

    # File lib/prawn/outline.rb, line 15
15:     def outline
16:       @outline ||=
17:     end
pad(y) click to toggle source

Moves down the document by y, executes a block, then moves down the document by y again.

  pdf.text "some text"
  pdf.pad(100) do
    pdf.text "This is 100 points below the previous line of text"
  pdf.text "This is 100 points below the previous line of text"
     # File lib/prawn/document.rb, line 449
449:     def pad(y)
450:       move_down(y)
451:       yield
452:       move_down(y)
453:     end
pad_bottom(y) click to toggle source

Executes a block then moves down the document

  pdf.text "some text"
  pdf.pad_bottom(100) do
    pdf.text "This text appears right below the previous line of text"
  pdf.text "This is 100 points below the previous line of text"
     # File lib/prawn/document.rb, line 435
435:     def pad_bottom(y)
436:       yield
437:       move_down(y)
438:     end
pad_top(y) click to toggle source

Moves down the document and then executes a block.

  pdf.text "some text"
  pdf.pad_top(100) do
    pdf.text "This is 100 points below the previous line of text"
  pdf.text "This text appears right below the previous line of text"
     # File lib/prawn/document.rb, line 422
422:     def pad_top(y)
423:       move_down(y)
424:       yield
425:     end
page() click to toggle source
     # File lib/prawn/document.rb, line 223
223:      def page
225:      end
page_count() click to toggle source

Returns the number of pages in the document

  pdf =
  pdf.page_count #=> 1
  3.times { pdf.start_new_page }
  pdf.page_count #=> 4
     # File lib/prawn/document.rb, line 287
287:     def page_count
288:       state.page_count
289:     end
page_match?(page_filter, page_number) click to toggle source

Provides a way to execute a block of code repeatedly based on a page_filter.

Available page filters are:

  :all         repeats on every page
  :odd         repeats on odd pages
  :even        repeats on even pages
  some_array   repeats on every page listed in the array
  some_range   repeats on every page included in the range
  some_lambda  yields page number and repeats for true return values 
     # File lib/prawn/document.rb, line 591
591:     def page_match?(page_filter, page_number)
592:       case page_filter
593:       when :all
594:         true
595:       when :odd
596:         page_number % 2 == 1
597:       when :even
598:         page_number % 2 == 0
599:       when Range, Array
600:         page_filter.include?(page_number)
601:       when Proc
603:       end
604:     end
render() click to toggle source

Renders the PDF document to string

     # File lib/prawn/document.rb, line 338
338:     def render
339:       output =
340:       finalize_all_page_contents
342:       render_header(output)
343:       render_body(output)
344:       render_xref(output)
345:       render_trailer(output)
346:       str = output.string
347:       str.force_encoding("ASCII-8BIT") if str.respond_to?(:force_encoding)
348:       str
349:     end
render_file(filename) click to toggle source

Renders the PDF document to file.

  pdf.render_file "foo.pdf"
     # File lib/prawn/document.rb, line 355
355:     def render_file(filename)
356:       Kernel.const_defined?("Encoding") ? mode = "wb:ASCII-8BIT" : mode = "wb"
357:,mode) { |f| f << render }
358:     end
repeat(page_filter, options={}, &block) click to toggle source

Provides a way to execute a block of code repeatedly based on a page_filter. Since Stamp is used under the hood, this method is very space efficient.

Available page filters are:

  :all        -- repeats on every page
  :odd        -- repeats on odd pages
  :even       -- repeats on even pages
  some_array  -- repeats on every page listed in the array
  some_range  -- repeats on every page included in the range
  some_lambda -- yields page number and repeats for true return values 

Also accepts an optional second argument for dynamic content which executes the code in the context of the filtered pages without using a Stamp.


  Prawn::Document.generate("repeat.pdf", :skip_page_creation => true) do

    repeat :all do
      draw_text "ALLLLLL", :at => bounds.top_left

    repeat :odd do
      draw_text "ODD", :at => [0,0]

    repeat :even do
      draw_text "EVEN", :at => [0,0]

    repeat [1,2] do 
      draw_text "[1,2]", :at => [100,0]

    repeat 2..4 do
      draw_text "2..4", :at => [200,0]

    repeat(lambda { |pg| pg % 3 == 0 }) do
      draw_text "Every third", :at => [250, 20]

    10.times do 
      draw_text "A wonderful page", :at => [400,400]
    repeat(:all, :dynamic => true) do
      text page_number, :at => [500, 0]

    # File lib/prawn/repeater.rb, line 76
76:     def repeat(page_filter, options={}, &block)
77:       repeaters <<, page_filter, !!options[:dynamic], &block)
78:     end
repeaters() click to toggle source

A list of all repeaters in the document. See Document#repeat for details

    # File lib/prawn/repeater.rb, line 18
18:     def repeaters
19:       @repeaters ||= []
20:     end
save_font() click to toggle source

Saves the current font, and then yields. When the block finishes, the original font is restored.

     # File lib/prawn/font.rb, line 111
111:     def save_font
112:       @font ||= find_font("Helvetica")
113:       original_font = @font
114:       original_size = @font_size
116:       yield
117:     ensure
118:       set_font(original_font, original_size) if original_font
119:     end
span(width, options={}) click to toggle source

A span is a special purpose bounding box that allows a column of elements to be positioned relative to the margin_box.



The width of the column in PDF points



One of :left, :center, :right or an x offset

This method is typically used for flowing a column of text from one page to the next.

 span(350, :position => :center) do
   text "Here's some centered text in a 350 point column. " * 100
    # File lib/prawn/document/span.rb, line 27
27:     def span(width, options={})
28:       Prawn.verify_options [:position], options
29:       original_position = self.y      
31:       # FIXME: Any way to move this upstream?
32:       left_boundary = case(options[:position] || :left)
33:       when :left
34:         margin_box.absolute_left
35:       when :center
36:         margin_box.absolute_left + margin_box.width / 2.0 - width /2.0
37:       when :right
38:         margin_box.absolute_right - width
39:       when Numeric
40:         margin_box.absolute_left + options[:position]
41:       else
42:         raise ArgumentError, "Invalid option for :position"
43:       end
45:       # we need to bust out of whatever nested bounding boxes we're in.
46:       canvas do
47:         bounding_box([left_boundary, 
48:                       margin_box.absolute_top], :width => width) do
49:           self.y = original_position
50:           yield
51:         end
52:       end          
53:     end
54:   end
55: end
start_new_page(options = {}) click to toggle source

Creates and advances to a new page in the document.

Page size, margins, and layout can also be set when generating a new page. These values will become the new defaults for page creation

  pdf.start_new_page #=> Starts new page keeping current values
  pdf.start_new_page(:size => "LEGAL", :layout => :landscape)
  pdf.start_new_page(:left_margin => 50, :right_margin => 50)
  pdf.start_new_page(:margin => 100)

A template for a page can be specified by pointing to the path of and existing pdf. One can also specify which page of the template which defaults otherwise to 1.

 pdf.start_new_page(:template => multipage_template.pdf, :template_page => 2)
     # File lib/prawn/document.rb, line 242
242:      def start_new_page(options = {})
243:        if last_page =
244:          last_page_size    = last_page.size
245:          last_page_layout  = last_page.layout
246:          last_page_margins = last_page.margins
247:        end
249:        page_options = {:size => options[:size] || last_page_size,
250:                        :layout  => options[:layout] || last_page_layout,
251:                        :margins => last_page_margins}
252:        if last_page
253:          new_graphic_state = last_page.graphic_state.dup
254:          #erase the color space so that it gets reset on new page for fussy pdf-readers
255:          new_graphic_state.color_space = {}
256:          page_options.merge!(:graphic_state => new_graphic_state)
257:        end
258:        merge_template_options(page_options, options) if options[:template]
260: =, page_options)
262:        apply_margin_options(options)
263: if options[:template]
264:        use_graphic_settings(options[:template])
266:        unless options[:orphan]
267:          state.insert_page(, @page_number)
268:          @page_number += 1
270:          canvas { image(@background, :at => bounds.top_left) } if @background
271:          @y = @bounding_box.absolute_top
273:          float do
274:            state.on_page_create_action(self)
275:          end
276:        end
278:      end
state() click to toggle source
     # File lib/prawn/document.rb, line 219
219:      def state
220:        @internal_state
221:      end
table(data, options={}, &block) click to toggle source

Set up and draw a table on this document. A block can be given, which will be run after cell setup but before layout and drawing.

See the documentation on Prawn::Table for details on the arguments.

    # File lib/prawn/table.rb, line 24
24:     def table(data, options={}, &block)
25:       t =, self, options, &block)
26:       t.draw
27:       t
28:     end
width_of(string, options={}) click to toggle source

Returns the width of the given string using the given font. If :size is not specified as one of the options, the string is measured using the current font size. You can also pass :kerning as an option to indicate whether kerning should be used when measuring the width (defaults to false).

Note that the string must be encoded properly for the font being used. For AFM fonts, this is WinAnsi. For TTF, make sure the font is encoded as UTF-8. You can use the Font#normalize_encoding method to make sure strings are in an encoding appropriate for the current font.

     # File lib/prawn/font.rb, line 219
219:     def width_of(string, options={})
220:       font.compute_width_of(string, options) + character_spacing * string.length
221:     end
y=(new_y) click to toggle source
     # File lib/prawn/document.rb, line 303
303:     def y=(new_y)
304:       @y = new_y
305:       bounds.update_height
306:     end

Private Instance Methods

apply_margin_options(options) click to toggle source
     # File lib/prawn/document.rb, line 657
657:     def apply_margin_options(options)
658:       if options[:margin]
659:         # Treat :margin as CSS shorthand with 1-4 values.
660:         margin = Array(options[:margin])
661:         positions = { 4 => [0,1,2,3], 3 => [0,1,2,1],
662:                       2 => [0,1,0,1], 1 => [0,0,0,0] }[margin.length]
664:         [:top, :right, :bottom, :left].zip(positions).each do |p,i|
665:           options[:"#{p}_margin"] ||= margin[i]
666:         end
667:       end
669:       [:left,:right,:top,:bottom].each do |side|
670:          if margin = options[:"#{side}_margin"]
671:  [side] = margin
672:          end
673:       end
675:       generate_margin_box
676:     end
generate_margin_box() click to toggle source
     # File lib/prawn/document.rb, line 632
632:     def generate_margin_box
633:       old_margin_box = @margin_box
634:       page           =
636:       @margin_box =
637:         self,
638:         nil,  # margin box has no parent
639:         [ page.margins[:left], page.dimensions[1] - page.margins[:top] ] ,
640:         :width => page.dimensions[2] - (page.margins[:left] + page.margins[:right]),
641:         :height => page.dimensions[1] - (page.margins[:top] + page.margins[:bottom])
642:       )
644:       # This check maintains indentation settings across page breaks
645:       if (old_margin_box)
646:         @margin_box.add_left_padding(old_margin_box.total_left_padding)
647:         @margin_box.add_right_padding(old_margin_box.total_right_padding)
648:       end
650:       # we must update bounding box if not flowing from the previous page
651:       #
652:       # FIXME: This may have a bug where the old margin is restored
653:       # when the bounding box exits.
654:       @bounding_box = @margin_box if old_margin_box == @bounding_box
655:     end
init_bounding_box(user_block, options={}, &init_block) click to toggle source
     # File lib/prawn/document/bounding_box.rb, line 183
183:     def init_bounding_box(user_block, options={}, &init_block)
184:       parent_box = @bounding_box
188:       self.y = @bounding_box.absolute_top
190:       self.y = @bounding_box.absolute_bottom unless options[:hold_position]
192:       created_box, @bounding_box = @bounding_box, parent_box
194:       return created_box
195:     end
init_column_box(user_block, options={}, &init_block) click to toggle source
    # File lib/prawn/document/column_box.rb, line 32
32:     def init_column_box(user_block, options={}, &init_block)
33:       parent_box = @bounding_box
37:       self.y = @bounding_box.absolute_top
39:       self.y = @bounding_box.absolute_bottom unless options[:hold_position]
41:       @bounding_box = parent_box
42:     end
merge_template_options(page_options, options) click to toggle source
     # File lib/prawn/document.rb, line 616
616:     def merge_template_options(page_options, options)
617:       object_id =[:template], options[:template_page] || 1)
618:       page_options.merge!(:object_id => object_id )
619:     end
multi_box(b1, b2) click to toggle source
     # File lib/prawn/layout/grid.rb, line 255
255:     def multi_box(b1, b2)
256:, b1, b2)
257:     end
single_box(i, j) click to toggle source
     # File lib/prawn/layout/grid.rb, line 251
251:     def single_box(i, j)
252:, i, j)
253:     end
use_graphic_settings(override_settings = false) click to toggle source

setting override_settings to true ensures that a new graphic state does not end up using previous settings especially from imported template streams

     # File lib/prawn/document.rb, line 623
623:     def use_graphic_settings(override_settings = false)
624:       set_fill_color if current_fill_color != "000000" || override_settings
625:       set_stroke_color if current_stroke_color != "000000" || override_settings
626:       write_line_width if line_width != 1 || override_settings
627:       write_stroke_cap_style if cap_style != :butt || override_settings
628:       write_stroke_join_style if join_style != :miter || override_settings
629:       write_stroke_dash if dashed? || override_settings
630:     end

Disabled; run with --debug to generate this.


Generated with the Darkfish Rdoc Generator 1.1.6.