Class: Prawn::Document
- Inherits:
-
Object
- Object
- Prawn::Document
- Includes:
- PDF::Core::Annotations, PDF::Core::Destinations, Security, Graphics, Images, SoftMask, Stamp, Text, TransformationStack
- Defined in:
- lib/prawn/document.rb,
lib/prawn/grid.rb,
lib/prawn/font.rb,
lib/prawn/outline.rb,
lib/prawn/security.rb,
lib/prawn/repeater.rb,
lib/prawn/document/span.rb,
lib/prawn/document/internals.rb,
lib/prawn/document/column_box.rb,
lib/prawn/document/bounding_box.rb
Overview
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 = Prawn::Document.new
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"
end
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
end
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.
Defined Under Namespace
Modules: Security Classes: BoundingBox, ColumnBox, Grid, GridBox, MultiBox
Constant Summary
- VALID_OPTIONS =
NOTE: We probably need to rethink the options validation system, but this constant temporarily allows for extensions to modify the list.
[:page_size, :page_layout, :margin, :left_margin, :right_margin, :top_margin, :bottom_margin, :skip_page_creation, :compress, :background, :info, :text_formatter, :print_scaling]
Constants included from Graphics
Constants included from Graphics::JoinStyle
Graphics::JoinStyle::JOIN_STYLES
Constants included from Graphics::CapStyle
Graphics::CapStyle::CAP_STYLES
Stable Attributes (collapse)
-
- (Object) margin_box
Returns the value of attribute margin_box.
-
- (Object) margins
readonly
Returns the value of attribute margins.
-
- (Object) page_number
Returns the value of attribute page_number.
-
- (Object) y
Returns the value of attribute y.
Extension Attributes (collapse)
-
- (Object) text_formatter
Returns the value of attribute text_formatter.
Experimental API (collapse)
-
- (Object) column_box(*args, &block)
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.
-
- (Object) define_grid(options = {})
Defines the grid system for a particular document.
-
- (Object) font_registry
Hash of Font objects keyed by names.
-
- (Object) grid(*args)
A method that can either be used to access a particular grid on the page or work with the grid system directly.
-
- (Boolean) page_match?(page_filter, page_number)
Provides a way to execute a block of code repeatedly based on a page_filter.
-
- (Object) repeat(page_filter, options = {}, &block)
Provides a way to execute a block of code repeatedly based on a page_filter.
-
- (Object) save_font
Saves the current font, and then yields.
-
- (Object) set_font(font, size = nil)
Sets the font directly, given an actual Font object and size.
Stable API (collapse)
-
+ (Object) generate(filename, options = {}, &block)
Creates and renders a PDF document.
-
- (Object) bounding_box(pt, *args, &block)
:call-seq: bounding_box(point, options={}, &block).
-
- (Object) bounds
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.
-
- (Object) bounds=(bounding_box)
Sets Document#bounds to the BoundingBox provided.
-
- (Object) canvas(&block)
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.
-
- (Object) cursor
The current y drawing position relative to the innermost bounding box, or to the page margins at the top level.
-
- (Object) float
Executes a block and then restores the original y position.
-
- (Object) font(name = nil, options = {})
Without arguments, this returns the currently selected font.
-
- (Object) font_families
Hash that maps font family names to their styled individual font names.
-
- (Object) font_size(points = nil)
When called with no argument, returns the current font size.
-
- (Object) font_size=(size)
Sets the font size.
-
- (Object) go_to_page(k)
Re-opens the page with the given (1-based) page number so that you can draw on it.
-
- (Object) indent(left, right = 0, &block)
Indents the specified number of PDF points for the duration of the block.
-
- (Document) initialize(options = {}, &block)
constructor
Creates a new PDF Document.
-
- (Object) move_cursor_to(new_y)
Moves to the specified y position in relative terms to the bottom margin.
-
- (Object) move_down(n)
Moves down the document by n points relative to the current position inside the current bounding box.
-
- (Object) move_up(n)
Moves up the document by n points relative to the current position inside the current bounding box.
-
- (Object) number_pages(string, options = {})
Places a text box on specified pages for page numbering.
-
- (Object) outline
Lazily instantiates a Prawn::Outline object for document.
-
- (Object) pad(y)
Moves down the document by y, executes a block, then moves down the document by y again.
-
- (Object) pad_bottom(y)
Executes a block then moves down the document.
-
- (Object) pad_top(y)
Moves down the document and then executes a block.
-
- (Object) page_count
Returns the number of pages in the document.
-
- (Object) render(*a, &b)
Renders the PDF document to string.
-
- (Object) render_file(filename)
Renders the PDF document to file.
-
- (Object) span(width, options = {})
A span is a special purpose bounding box that allows a column of elements to be positioned relative to the margin_box.
-
- (Object) start_new_page(options = {})
Creates and advances to a new page in the document.
-
- (Object) width_of(string, options = {})
Returns the width of the given string using the given font.
Extension API (collapse)
-
+ (Object) extensions
Any module added to this array will be included into instances of Prawn::Document at the per-object level.
- - (Object) initialize_first_page(options)
Methods included from TransformationStack
#add_to_transformation_stack, #current_transformation_matrix_with_translation, #restore_transformation_stack, #save_transformation_stack
Methods included from SoftMask
Methods included from Stamp
#create_stamp, #stamp, #stamp_at
Methods included from Images
Methods included from Graphics
#circle, #close_and_stroke, #close_path, #curve, #curve_to, #ellipse, #fill, #fill_and_stroke, #horizontal_line, #horizontal_rule, #line, #line_to, #line_width, #line_width=, #move_to, #polygon, #rectangle, #rounded_polygon, #rounded_rectangle, #rounded_vertex, #stroke, #stroke_axis, #stroke_bounds, #vertical_line
Methods included from Graphics::Patterns
#fill_gradient, #stroke_gradient
Methods included from Graphics::Transformation
#rotate, #scale, #transformation_matrix, #translate
Methods included from Graphics::Transparency
Methods included from Graphics::JoinStyle
Methods included from Graphics::CapStyle
Methods included from Graphics::Dash
Methods included from Graphics::Color
#fill_color, hex2rgb, rgb2hex, #stroke_color
Methods included from Graphics::BlendMode
Methods included from Text
#draw_text, #draw_text!, #formatted_text, #height_of, #height_of_formatted, #text, #text_box
Methods included from Text::Formatted
Methods included from Security
#encrypt_document, encrypt_string
Constructor Details
- (Document) initialize(options = {}, &block)
Creates a new PDF Document. The following options are available (with the default values marked in [])
:page_size
-
One of the PDF::Core::PageGeometry sizes [LETTER]
:page_layout
-
Either
:portrait
or:landscape
:margin
-
Sets the margin on all sides in points [0.5 inch]
:left_margin
-
Sets the left margin in points [0.5 inch]
:right_margin
-
Sets the right margin in points [0.5 inch]
:top_margin
-
Sets the top margin in points [0.5 inch]
:bottom_margin
-
Sets the bottom margin in points [0.5 inch]
:skip_page_creation
-
Creates a document without starting the first page [false]
:compress
-
Compresses content streams before rendering them [false]
:background
-
An image path to be used as background on all pages [nil]
:background_scale
-
Backgound image scale [1] [nil]
:info
-
Generic hash allowing for custom metadata properties [nil]
:text_formatter
: The text formatter to use for
:inline_format
ted text [Prawn::Text::Formatted::Parser]
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.
Usage:
# New document, US Letter paper, portrait orientation
pdf = Prawn::Document.new
# New document, A4 paper, landscaped
pdf = Prawn::Document.new(:page_size => "A4", :page_layout => :landscape)
# New document, Custom size
pdf = Prawn::Document.new(:page_size => [200, 300])
# New document, with background
pdf = Prawn::Document.new(:background => "#{Prawn::DATADIR}/images/pigs.jpg")
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
# File 'lib/prawn/document.rb', line 192 def initialize( = {}, &block) = .dup Prawn. VALID_OPTIONS, # need to fix, as the refactoring breaks this # raise NotImplementedError if options[:skip_page_creation] self.class.extensions.reverse_each { |e| extend e } self.state = PDF::Core::DocumentState.new() self.state.populate_pages_from_store(self) renderer.min_version(state.store.min_version) if state.store.min_version renderer.min_version(1.6) if [:print_scaling] == :none @background = [:background] @background_scale = [:background_scale] || 1 @font_size = 12 @bounding_box = nil @margin_box = nil @page_number = 0 @text_formatter = .delete(:text_formatter) || Text::Formatted::Parser [:size] = .delete(:page_size) [:layout] = .delete(:page_layout) initialize_first_page() @bounding_box = @margin_box if block block.arity < 1 ? instance_eval(&block) : block[self] end end |
Instance Attribute Details
- (Object) margin_box
Returns the value of attribute margin_box
104 105 106 |
# File 'lib/prawn/document.rb', line 104 def margin_box @margin_box end |
- (Object) margins (readonly)
Returns the value of attribute margins
105 106 107 |
# File 'lib/prawn/document.rb', line 105 def margins @margins end |
- (Object) page_number
Returns the value of attribute page_number
106 107 108 |
# File 'lib/prawn/document.rb', line 106 def page_number @page_number end |
- (Object) text_formatter
Returns the value of attribute text_formatter
110 111 112 |
# File 'lib/prawn/document.rb', line 110 def text_formatter @text_formatter end |
- (Object) y
Returns the value of attribute y
105 106 107 |
# File 'lib/prawn/document.rb', line 105 def y @y end |
Class Method Details
+ (Object) extensions
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.
Example:
module MyFancyModule
def party!
text "It's a big party!"
end
end
Prawn::Document.extensions << MyFancyModule
Prawn::Document.generate("foo.pdf") do
party!
end
93 94 95 |
# File 'lib/prawn/document.rb', line 93 def self.extensions @extensions ||= [] end |
+ (Object) generate(filename, options = {}, &block)
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
end
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
end
141 142 143 144 |
# File 'lib/prawn/document.rb', line 141 def self.generate(filename, = {}, &block) pdf = new(, &block) pdf.render_file(filename) end |
Instance Method Details
- (Object) bounding_box(pt, *args, &block)
:call-seq:
bounding_box(point, ={}, &block)
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)
Positioning
Bounding boxes are positioned relative to their top left corner and the width measurement is towards the right and height measurement is downwards.
Usage:
-
Bounding box 100pt x 100pt in the absolute bottom left of the containing box:
pdf.bounding_box(, :width => 100, :height => 100)
stroke_bounds
end
-
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
stroke_bounds
end
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.
Usage:
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"
end
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]
end
end
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
Usage:
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.
pdf.stroke_bounds
end
end
Stretchyness
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}")
end
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.stroke_bounds
pdf.canvas do
Positioned outside the containing box at the 'real' (300,450)
pdf.bounding_box([300,450], :width => 200, :height => 200) do
pdf.stroke_bounds
end
end
end
Of course, if you use canvas, you will be responsible for ensuring that you remain within the printable area of your document.
158 159 160 161 162 163 |
# File 'lib/prawn/document/bounding_box.rb', line 158 def bounding_box(pt, *args, &block) init_bounding_box(block) do |parent_box| pt = map_to_absolute(pt) @bounding_box = BoundingBox.new(self, parent_box, pt, *args) end end |
- (Object) bounds
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:
Prawn::Document.new 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)
end
# Draw a border around the page (the easy way)
stroke_bounds
end
398 399 400 |
# File 'lib/prawn/document.rb', line 398 def bounds @bounding_box end |
- (Object) bounds=(bounding_box)
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.
414 415 416 |
# File 'lib/prawn/document.rb', line 414 def bounds=(bounding_box) @bounding_box = bounding_box end |
- (Object) canvas(&block)
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
end
172 173 174 175 176 177 178 179 180 181 |
# File 'lib/prawn/document/bounding_box.rb', line 172 def canvas(&block) init_bounding_box(block, :hold_position => true) do |_| # Canvas bbox acts like margin_box in that its parent bounds are unset. @bounding_box = BoundingBox.new( self, nil, [0, page.dimensions[3]], :width => page.dimensions[2], :height => page.dimensions[3] ) end end |
- (Object) column_box(*args, &block)
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. If resetting the top margin is desired on a new page (e.g. to allow for initial page wide column titles) the option :reflow_margins => true can be set.
Defaults are :columns = 3, :spacer = font_size, and :reflow_margins => false
Under PDF::Writer, “spacer” was known as “gutter”
30 31 32 33 34 35 |
# File 'lib/prawn/document/column_box.rb', line 30 def column_box(*args, &block) init_column_box(block) do |parent_box| map_to_absolute!(args[0]) @bounding_box = ColumnBox.new(self, parent_box, *args) end end |
- (Object) cursor
The current y drawing position relative to the innermost bounding box, or to the page margins at the top level.
320 321 322 |
# File 'lib/prawn/document.rb', line 320 def cursor y - bounds.absolute_bottom end |
- (Object) define_grid(options = {})
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
Note that a completely new grid object is built each time define_grid() is called. This means that all subsequent calls to grid() will use the newly defined Grid object – grids are not nestable like bounding boxes are.
22 23 24 25 |
# File 'lib/prawn/grid.rb', line 22 def define_grid( = {}) @boxes = nil @grid = Grid.new(self, ) end |
- (Object) float
Executes a block and then restores the original y position. If new pages were created during this block, it will teleport back to the original page when done.
pdf.text "A"
pdf.float do
pdf.move_down 100
pdf.text "C"
end
pdf.text "B"
343 344 345 346 347 348 349 |
# File 'lib/prawn/document.rb', line 343 def float original_page = page_number original_y = y yield go_to_page(original_page) unless page_number == original_page self.y = original_y end |
- (Object) font(name = nil, options = {})
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("DejaVuSans.ttf") do
text "Using TTF font from file DejaVuSans.ttf"
font "Courier", :style => :bold
text "You see this in bold Courier"
end
text "Times-Roman, again"
end
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.
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/prawn/font.rb', line 50 def font(name = nil, = {}) return((defined?(@font) && @font) || font("Helvetica")) if name.nil? if state.pages.empty? && !state.page.in_stamp_stream? fail Prawn::Errors::NotOnPage end new_font = find_font(name.to_s, ) if block_given? save_font do set_font(new_font, [:size]) yield end else set_font(new_font, [:size]) end @font end |
- (Object) font_families
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:
pdf.font_families.update(
"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.font("MyTrueTypeFamily")
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”. When defining your own font families, you can map any or all of these styles to whatever font files you'd like.
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
# File 'lib/prawn/font.rb', line 170 def font_families @font_families ||= {}.merge!( "Courier" => { :bold => "Courier-Bold", :italic => "Courier-Oblique", :bold_italic => "Courier-BoldOblique", :normal => "Courier" }, "Times-Roman" => { :bold => "Times-Bold", :italic => "Times-Italic", :bold_italic => "Times-BoldItalic", :normal => "Times-Roman" }, "Helvetica" => { :bold => "Helvetica-Bold", :italic => "Helvetica-Oblique", :bold_italic => "Helvetica-BoldOblique", :normal => "Helvetica" } ) end |
- (Object) font_registry
Hash of Font objects keyed by names
249 250 251 |
# File 'lib/prawn/font.rb', line 249 def font_registry #:nodoc: @font_registry ||= {} end |
- (Object) font_size(points = nil)
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"
end
text "At size 16"
end
When called without an argument, this method returns the current font size.
97 98 99 100 101 102 103 |
# File 'lib/prawn/font.rb', line 97 def font_size(points = nil) return @font_size unless points size_before_yield = @font_size @font_size = points block_given? ? yield : return @font_size = size_before_yield end |
- (Object) font_size=(size)
Sets the font size
106 107 108 |
# File 'lib/prawn/font.rb', line 106 def font_size=(size) font_size(size) end |
- (Object) go_to_page(k)
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.
305 306 307 308 309 310 |
# File 'lib/prawn/document.rb', line 305 def go_to_page(k) @page_number = k state.page = state.pages[k - 1] generate_margin_box @y = @bounding_box.absolute_top end |
- (Object) grid(*args)
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 GridBox at [0,1]
@pdf.grid([0,1], [1,2]) # Get a multi-box spanning from [0,1] to [1,2]
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/prawn/grid.rb', line 34 def grid(*args) @boxes ||= {} return @boxes[args] if @boxes[args] if args.empty? @boxes[args] = @grid else g1, g2 = args if g1.class == Array && g2.class == Array && g1.length == 2 && g2.length == 2 @boxes[args] = multi_box(single_box(*g1), single_box(*g2)) else @boxes[args] = single_box(g1, g2) end end @boxes[args] end |
- (Object) indent(left, right = 0, &block)
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"
end
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."
end
485 486 487 |
# File 'lib/prawn/document.rb', line 485 def indent(left, right = 0, &block) bounds.indent(left, right, &block) end |
- (Object) initialize_first_page(options)
631 632 633 634 635 636 637 |
# File 'lib/prawn/document.rb', line 631 def initialize_first_page() if [:skip_page_creation] start_new_page(.merge(:orphan => true)) else start_new_page() end end |
- (Object) move_cursor_to(new_y)
Moves to the specified y position in relative terms to the bottom margin.
326 327 328 |
# File 'lib/prawn/document.rb', line 326 def move_cursor_to(new_y) self.y = new_y + bounds.absolute_bottom end |
- (Object) move_down(n)
Moves down the document by n points relative to the current position inside the current bounding box.
428 429 430 |
# File 'lib/prawn/document.rb', line 428 def move_down(n) self.y -= n end |
- (Object) move_up(n)
Moves up the document by n points relative to the current position inside the current bounding box.
421 422 423 |
# File 'lib/prawn/document.rb', line 421 def move_up(n) self.y += n end |
- (Object) number_pages(string, options = {})
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, <page> refers to the current page, and <total> 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:
string
-
Template string for page number wording. Should include '<page>' and, optionally, '<total>'.
options
-
A hash for page numbering and text box options.
:page_filter
-
A filter to specify which pages to place page numbers on. Refer to the method 'page_match?'
:start_count_at
-
The starting count to increment pages from.
:total_pages
-
If provided, will replace <total> with the value given. Useful to override the total number of pages when using the start_count_at option.
:color
-
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
five.
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}
end
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
# File 'lib/prawn/document.rb', line 524 def number_pages(string, = {}) opts = .dup start_count_at = opts.delete(:start_count_at).to_i if opts.key?(:page_filter) page_filter = opts.delete(:page_filter) else page_filter = :all end total_pages = opts.delete(:total_pages) txtcolor = opts.delete(:color) # An explicit height so that we can draw page numbers in the margins opts[:height] = 50 unless opts.key?(:height) start_count = false pseudopage = 0 (1..page_count).each do |p| unless start_count pseudopage = case start_count_at when 0 1 else start_count_at.to_i end end if page_match?(page_filter, p) go_to_page(p) # have to use fill_color here otherwise text reverts back to default fill color fill_color txtcolor unless txtcolor.nil? total_pages = total_pages.nil? ? page_count : total_pages str = string.gsub("<page>", "#{pseudopage}").gsub("<total>", "#{total_pages}") text_box str, opts start_count = true # increment page count as soon as first match found end pseudopage += 1 if start_count end end |
- (Object) outline
Lazily instantiates a Prawn::Outline object for document. This is used as point of entry to methods to build the outline tree for a document's table of contents.
9 10 11 |
# File 'lib/prawn/outline.rb', line 9 def outline @outline ||= Outline.new(self) end |
- (Object) pad(y)
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"
end
pdf.text "This is 100 points below the previous line of text"
467 468 469 470 471 |
# File 'lib/prawn/document.rb', line 467 def pad(y) move_down(y) yield move_down(y) end |
- (Object) pad_bottom(y)
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"
end
pdf.text "This is 100 points below the previous line of text"
453 454 455 456 |
# File 'lib/prawn/document.rb', line 453 def pad_bottom(y) yield move_down(y) end |
- (Object) pad_top(y)
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"
end
pdf.text "This text appears right below the previous line of text"
440 441 442 443 |
# File 'lib/prawn/document.rb', line 440 def pad_top(y) move_down(y) yield end |
- (Object) page_count
Returns the number of pages in the document
pdf = Prawn::Document.new
pdf.page_count #=> 1
3.times { pdf.start_new_page }
pdf.page_count #=> 4
296 297 298 |
# File 'lib/prawn/document.rb', line 296 def page_count state.page_count end |
- (Boolean) page_match?(page_filter, page_number)
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
602 603 604 605 606 607 608 609 610 611 612 613 614 615 |
# File 'lib/prawn/document.rb', line 602 def page_match?(page_filter, page_number) case page_filter when :all true when :odd page_number.odd? when :even page_number.even? when Range, Array page_filter.include?(page_number) when Proc page_filter.call(page_number) end end |
- (Object) render(*a, &b)
Renders the PDF document to string. Pass an open file descriptor to render to file.
354 355 356 357 358 359 360 361 |
# File 'lib/prawn/document.rb', line 354 def render(*a, &b) (1..page_count).each do |i| go_to_page i repeaters.each { |r| r.run(i) } end renderer.render(*a, &b) end |
- (Object) render_file(filename)
Renders the PDF document to file.
pdf.render_file "foo.pdf"
367 368 369 |
# File 'lib/prawn/document.rb', line 367 def render_file(filename) File.open(filename, "wb") { |f| render(f) } end |
- (Object) repeat(page_filter, options = {}, &block)
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.
Example:
Prawn::Document.generate("repeat.pdf", :skip_page_creation => true) do
repeat :all do
draw_text "ALLLLLL", :at => bounds.top_left
end
repeat :odd do
draw_text "ODD", :at => [0,0]
end
repeat :even do
draw_text "EVEN", :at => [0,0]
end
repeat [1,2] do
draw_text "[1,2]", :at => [100,0]
end
repeat 2..4 do
draw_text "2..4", :at => [200,0]
end
repeat(lambda { |pg| pg % 3 == 0 }) do
draw_text "Every third", :at => [250, 20]
end
10.times do
start_new_page
draw_text "A wonderful page", :at => [400,400]
end
repeat(:all, :dynamic => true) do
text page_number, :at => [500, 0]
end
end
77 78 79 |
# File 'lib/prawn/repeater.rb', line 77 def repeat(page_filter, = {}, &block) repeaters << Prawn::Repeater.new(self, page_filter, !![:dynamic], &block) end |
- (Object) save_font
Saves the current font, and then yields. When the block finishes, the original font is restored.
202 203 204 205 206 207 208 209 210 |
# File 'lib/prawn/font.rb', line 202 def save_font @font ||= find_font("Helvetica") original_font = @font original_size = @font_size yield ensure set_font(original_font, original_size) if original_font end |
- (Object) set_font(font, size = nil)
Sets the font directly, given an actual Font object and size.
194 195 196 197 |
# File 'lib/prawn/font.rb', line 194 def set_font(font, size = nil) # :nodoc: @font = font @font_size = size if size end |
- (Object) span(width, options = {})
A span is a special purpose bounding box that allows a column of elements to be positioned relative to the margin_box.
Arguments:
width
-
The width of the column in PDF points
Options:
:position
-
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
end
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/prawn/document/span.rb', line 29 def span(width, = {}) Prawn. [:position], original_position = self.y # FIXME: Any way to move this upstream? left_boundary = case([:position] || :left) when :left margin_box.absolute_left when :center margin_box.absolute_left + margin_box.width / 2.0 - width / 2.0 when :right margin_box.absolute_right - width when Numeric margin_box.absolute_left + [:position] else fail ArgumentError, "Invalid option for :position" end # we need to bust out of whatever nested bounding boxes we're in. canvas do bounding_box([left_boundary, margin_box.absolute_top], :width => width) do self.y = original_position yield end end end |
- (Object) start_new_page(options = {})
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)
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
# File 'lib/prawn/document.rb', line 242 def start_new_page( = {}) if last_page = state.page last_page_size = last_page.size last_page_layout = last_page.layout last_page_margins = last_page.margins.dup end = { :size => [:size] || last_page_size, :layout => [:layout] || last_page_layout, :margins => last_page_margins } if last_page new_graphic_state = last_page.graphic_state.dup if last_page.graphic_state # erase the color space so that it gets reset on new page for fussy pdf-readers new_graphic_state.color_space = {} if new_graphic_state .merge!(:graphic_state => new_graphic_state) end state.page = PDF::Core::Page.new(self, ) () generate_margin_box # Reset the bounding box if the new page has different size or layout if last_page && (last_page.size != state.page.size || last_page.layout != state.page.layout) @bounding_box = @margin_box end use_graphic_settings unless [:orphan] state.insert_page(state.page, @page_number) @page_number += 1 canvas { image(@background, :scale => @background_scale, :at => bounds.top_left) } if @background @y = @bounding_box.absolute_top float do state.on_page_create_action(self) end end end |
- (Object) width_of(string, options = {})
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. – For the record, this method used to be a method of Font (and still delegates to width computations on Font). However, having the primary interface for calculating string widths exist on Font made it tricky to write extensions for Prawn in which widths are computed differently (e.g., taking formatting tags into account, or the like).
By putting width_of here, on Document itself, extensions may easily override it and redefine the width calculation behavior. ++
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
# File 'lib/prawn/font.rb', line 129 def width_of(string, = {}) if p = [:inline_format] p = [] unless p.is_a?(Array) # Build up an Arranger with the entire string on one line, finalize it, # and find its width. arranger = Prawn::Text::Formatted::Arranger.new(self, ) arranger.consumed = self.text_formatter.format(string, *p) arranger.finalize_line arranger.line_width else width_of_string(string, ) end end |