Class: Prawn::Document
- Inherits:
-
Object
- Object
- Prawn::Document
- Includes:
- Annotations, Destinations, Internals, PageGeometry, Snapshot, Graphics, Images, Stamp, Text
- Defined in:
- lib/prawn/document.rb,
lib/prawn/font.rb,
lib/prawn/repeater.rb,
lib/prawn/document/span.rb,
lib/prawn/document/snapshot.rb,
lib/prawn/document/internals.rb,
lib/prawn/document/column_box.rb,
lib/prawn/document/annotations.rb,
lib/prawn/document/bounding_box.rb,
lib/prawn/document/destinations.rb,
lib/prawn/document/page_geometry.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: Annotations, Destinations, Internals, PageGeometry, Snapshot Classes: BoundingBox, ColumnBox
Constant Summary collapse
- CannotGroup =
Raised if group() is called with a block that is too big to be rendered in the current context.
Class.new(StandardError)
Constants included from Graphics
Constants included from Graphics::JoinStyle
Graphics::JoinStyle::JOIN_STYLES
Constants included from Graphics::CapStyle
Graphics::CapStyle::CAP_STYLES
Constants included from Snapshot
Constants included from Destinations
Destinations::NAME_TREE_CHILDREN_LIMIT
Constants included from PageGeometry
Constants included from Text
Instance Attribute Summary collapse
-
#font_size(points = nil) ⇒ Object
When called with no argument, returns the current font size.
-
#margin_box ⇒ Object
Returns the value of attribute margin_box.
-
#margins ⇒ Object
readonly
Returns the value of attribute margins.
-
#page_layout ⇒ Object
readonly
Returns the value of attribute page_layout.
-
#page_size ⇒ Object
readonly
Returns the value of attribute page_size.
-
#y ⇒ Object
Returns the value of attribute y.
Attributes included from Text
Class Method Summary collapse
-
.extensions ⇒ Object
Any module added to this array will be included into instances of Prawn::Document at the per-object level.
-
.generate(filename, options = {}, &block) ⇒ Object
Creates and renders a PDF document.
-
.inherited(base) ⇒ Object
:nodoc:.
- .move_past_bottom ⇒ Object
Instance Method Summary collapse
-
#bounding_box(*args, &block) ⇒ Object
:call-seq: bounding_box(point, options={}, &block) .
-
#bounds ⇒ Object
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.
-
#bounds=(bounding_box) ⇒ Object
Sets Document#bounds to the BoundingBox provided.
-
#canvas(&block) ⇒ Object
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.
-
#column_box(*args, &block) ⇒ Object
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.
-
#compression_enabled? ⇒ Boolean
Returns true if content streams will be compressed before rendering, false otherwise.
-
#cursor ⇒ Object
The current y drawing position relative to the innermost bounding box, or to the page margins at the top level.
-
#find_font(name, options = {}) ⇒ Object
Looks up the given font using the given criteria.
-
#float ⇒ Object
Executes a block and then restores the original y position.
-
#font(name = nil, options = {}) ⇒ Object
Without arguments, this returns the currently selected font.
-
#font_families ⇒ Object
Hash that maps font family names to their styled individual font names.
-
#font_registry ⇒ Object
Hash of Font objects keyed by names.
-
#go_to_page(k) ⇒ Object
Re-opens the page with the given (1-based) page number so that you can draw on it.
-
#group(second_attempt = false) ⇒ Object
Attempts to group the given block vertically within the current context.
-
#indent(x, &block) ⇒ Object
Indents the specified number of PDF points for the duration of the block.
-
#initialize(options = {}, &block) ⇒ Document
constructor
Creates a new PDF Document.
-
#mask(*fields) ⇒ Object
:nodoc:.
-
#move_cursor_to(new_y) ⇒ Object
Moves to the specified y position in relative terms to the bottom margin.
-
#move_down(n) ⇒ Object
Moves down the document by n points relative to the current position inside the current bounding box.
-
#move_up(n) ⇒ Object
Moves up the document by n points relative to the current position inside the current bounding box.
-
#number_pages(string, position) ⇒ Object
Specify a template for page numbering.
-
#pad(y) ⇒ Object
Moves down the document by y, executes a block, then moves down the document by y again.
-
#pad_bottom(y) ⇒ Object
Executes a block then moves down the document.
-
#pad_top(y) ⇒ Object
Moves down the document and then executes a block.
-
#page_count ⇒ Object
Returns the number of pages in the document.
-
#page_number ⇒ Object
Returns the 1-based page number of the current page.
-
#render ⇒ Object
Renders the PDF document to string.
-
#render_file(filename) ⇒ Object
Renders the PDF document to file.
-
#repeat(page_filter, &block) ⇒ Object
Provides a way to execute a block of code repeatedly based on a page_filter.
-
#repeaters ⇒ Object
A list of all repeaters in the document.
-
#save_font ⇒ Object
Saves the current font, and then yields.
-
#set_font(font, size = nil) ⇒ Object
Sets the font directly, given an actual Font object and size.
-
#span(width, options = {}) ⇒ Object
A span is a special purpose bounding box that allows a column of elements to be positioned relative to the margin_box.
-
#start_new_page(options = {}) ⇒ Object
Creates and advances to a new page in the document.
-
#width_of(string, options = {}) ⇒ Object
Returns the width of the given string using the given font.
Methods included from Stamp
#create_stamp, #stamp, #stamp_at
Methods included from Images
Methods included from Graphics
#circle_at, #curve, #curve_to, #ellipse_at, #fill, #fill_and_stroke, #horizontal_line, #horizontal_rule, #line, #line_to, #line_width, #line_width=, #move_to, #polygon, #rectangle, #stroke, #stroke_bounds, #vertical_line
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, #method_missing, rgb2hex, #stroke_color
Methods included from Snapshot
Methods included from Destinations
#add_dest, #dest_fit, #dest_fit_bounds, #dest_fit_bounds_horizontally, #dest_fit_bounds_vertically, #dest_fit_horizontally, #dest_fit_rect, #dest_fit_vertically, #dest_xyz, #dests
Methods included from Annotations
#annotate, #link_annotation, #text_annotation
Methods included from Internals
#add_content, #before_render, #current_page, #names, #names?, #on_page_create, #page_content, #page_ext_gstates, #page_fonts, #page_resources, #page_xobjects, #ref, #ref!
Methods included from PageGeometry
Methods included from Text
#height_of, #process_text_options, #text, #text_at, #text_box
Constructor Details
#initialize(options = {}, &block) ⇒ Document
Creates a new PDF Document. The following options are available (with the default values marked in [])
:page_size
-
One of the Document::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]
:optimize_objects
-
Reduce number of PDF objects in output, at expense of render time [false]
:background
-
An image path to be used as background on all pages [nil]
:info
-
Generic hash allowing for custom metadata properties [nil]
:text_options
-
A set of default options to be handed to text(). Be careful with this.
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::BASEDIR}/data/images/pigs.jpg")
178 179 180 181 182 183 184 185 186 187 188 189 190 191 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 229 230 231 232 233 |
# File 'lib/prawn/document.rb', line 178 def initialize(={},&block) Prawn. [:page_size, :page_layout, :margin, :left_margin, :right_margin, :top_margin, :bottom_margin, :skip_page_creation, :compress, :skip_encoding, :text_options, :background, :info, :optimize_objects], self.class.extensions.reverse_each { |e| extend e } [:info] ||= {} [:info][:Creator] ||= "Prawn" [:info][:Producer] = "Prawn" [:info].keys.each do |key| if [:info][key].kind_of?(String) [:info][key] = Prawn::LiteralString.new([:info][key]) end end @version = 1.3 @store = ObjectStore.new([:info]) @trailer = {} @before_render_callbacks = [] @on_page_create_callback = nil @page_size = [:page_size] || "LETTER" @page_layout = [:page_layout] || :portrait @compress = [:compress] || false @optimize_objects = .fetch(:optimize_objects, false) @skip_encoding = [:skip_encoding] @background = [:background] @font_size = 12 @page_content = nil @bounding_box = nil @margin_box = nil @text_options = [:text_options] || {} apply_margin_option() if [:margin] default_margin = 36 # 0.5 inch @margins = { :left => [:left_margin] || default_margin, :right => [:right_margin] || default_margin, :top => [:top_margin] || default_margin, :bottom => [:bottom_margin] || default_margin } generate_margin_box @bounding_box = @margin_box @page_number = 0 start_new_page unless [:skip_page_creation] if block block.arity < 1 ? instance_eval(&block) : block[self] end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class Prawn::Graphics::Color
Instance Attribute Details
#font_size(points = nil) ⇒ Object
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.
71 72 73 74 75 76 77 |
# File 'lib/prawn/font.rb', line 71 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 |
#margin_box ⇒ Object
Returns the value of attribute margin_box.
67 68 69 |
# File 'lib/prawn/document.rb', line 67 def margin_box @margin_box end |
#margins ⇒ Object (readonly)
Returns the value of attribute margins.
68 69 70 |
# File 'lib/prawn/document.rb', line 68 def margins @margins end |
#page_layout ⇒ Object (readonly)
Returns the value of attribute page_layout.
68 69 70 |
# File 'lib/prawn/document.rb', line 68 def page_layout @page_layout end |
#page_size ⇒ Object (readonly)
Returns the value of attribute page_size.
68 69 70 |
# File 'lib/prawn/document.rb', line 68 def page_size @page_size end |
#y ⇒ Object
Returns the value of attribute y.
68 69 70 |
# File 'lib/prawn/document.rb', line 68 def y @y end |
Class Method Details
.extensions ⇒ Object
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
92 93 94 |
# File 'lib/prawn/document.rb', line 92 def self.extensions @extensions ||= [] end |
.generate(filename, options = {}, &block) ⇒ Object
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"
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.text content, :at => [200,720], :size => 32
end
127 128 129 130 |
# File 'lib/prawn/document.rb', line 127 def self.generate(filename,={},&block) pdf = new(,&block) pdf.render_file(filename) end |
.inherited(base) ⇒ Object
:nodoc:
96 97 98 |
# File 'lib/prawn/document.rb', line 96 def self.inherited(base) #:nodoc: extensions.each { |e| base.extensions << e } end |
.move_past_bottom ⇒ Object
501 502 503 |
# File 'lib/prawn/document.rb', line 501 def @bounding_box.move_past_bottom raise RollbackTransaction end |
Instance Method Details
#bounding_box(*args, &block) ⇒ Object
: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
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.
154 155 156 157 158 159 |
# File 'lib/prawn/document/bounding_box.rb', line 154 def bounding_box(*args, &block) init_bounding_box(block) do |_| translate!(args[0]) @bounding_box = BoundingBox.new(self, *args) end end |
#bounds ⇒ Object
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
391 392 393 |
# File 'lib/prawn/document.rb', line 391 def bounds @bounding_box end |
#bounds=(bounding_box) ⇒ Object
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 existing bounding box code blocks is good enough.
400 401 402 |
# File 'lib/prawn/document.rb', line 400 def bounds=(bounding_box) @bounding_box = bounding_box end |
#canvas(&block) ⇒ Object
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
168 169 170 171 172 173 174 175 |
# File 'lib/prawn/document/bounding_box.rb', line 168 def canvas(&block) init_bounding_box(block, :hold_position => true) do |_| @bounding_box = BoundingBox.new(self, [0,page_dimensions[3]], :width => page_dimensions[2], :height => page_dimensions[3] ) end end |
#column_box(*args, &block) ⇒ Object
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”
23 24 25 26 27 28 |
# File 'lib/prawn/document/column_box.rb', line 23 def column_box(*args, &block) init_column_box(block) do |_| translate!(args[0]) @bounding_box = ColumnBox.new(self, *args) end end |
#compression_enabled? ⇒ Boolean
Returns true if content streams will be compressed before rendering, false otherwise
543 544 545 |
# File 'lib/prawn/document.rb', line 543 def compression_enabled? !!@compress end |
#cursor ⇒ Object
The current y drawing position relative to the innermost bounding box, or to the page margins at the top level.
314 315 316 |
# File 'lib/prawn/document.rb', line 314 def cursor y - bounds.absolute_bottom end |
#find_font(name, options = {}) ⇒ Object
Looks up the given font using the given criteria. Once a font has been found by that matches the criteria, it will be cached to subsequent lookups for that font will return the same object. – Challenges involved: the name alone is not sufficient to uniquely identify a font (think dfont suitcases that can hold multiple different fonts in a single file). Thus, the :name key is included in the cache key.
It is further complicated, however, since fonts in some formats (like the dfont suitcases) can be identified either by numeric index, OR by their name within the suitcase, and both should hash to the same font object (to avoid the font being embedded multiple times). This is not yet implemented, which means if someone selects a font both by name, and by index, the font will be embedded twice. Since we do font subsetting, this double embedding won’t be catastrophic, just annoying. ++
116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/prawn/font.rb', line 116 def find_font(name, ={}) #:nodoc: if font_families.key?(name) family, name = name, font_families[name][[:style] || :normal] if name.is_a?(Hash) = .merge(name) name = [:file] end end key = "#{name}:#{[:font] || 0}" font_registry[key] ||= Font.load(self, name, .merge(:family => family)) end |
#float ⇒ Object
Executes a block and then restores the original y position
pdf.text "A"
pdf.float do
pdf.move_down 100
pdf.text "C"
end
pdf.text "B"
336 337 338 |
# File 'lib/prawn/document.rb', line 336 def float mask(:y) { yield } end |
#font(name = nil, options = {}) ⇒ Object
Without arguments, this returns the currently selected font. Otherwise, it sets the current font.
The single 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.
pdf.font "Times-Roman"
pdf.font "Chalkboard.ttf"
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.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/prawn/font.rb', line 30 def font(name=nil, ={}) return((defined?(@font) && @font) || font("Helvetica")) if name.nil? raise Errors::NotOnPage unless current_page new_font = find_font(name, ) if block_given? save_font do set_font(new_font, [:size]) yield end else set_font(new_font, [:size]) end @font end |
#font_families ⇒ Object
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.
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
# File 'lib/prawn/font.rb', line 154 def font_families @font_families ||= Hash.new { |h,k| h[k] = {} }.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 |
#font_registry ⇒ Object
Hash of Font objects keyed by names
130 131 132 |
# File 'lib/prawn/font.rb', line 130 def font_registry #:nodoc: @font_registry ||= {} end |
#go_to_page(k) ⇒ Object
Re-opens the page with the given (1-based) page number so that you can draw on it. Does not restore page state such as margins, page orientation, or paper size, so you’ll have to handle that yourself.
See Prawn::Document#number_pages for a sample usage of this capability.
299 300 301 302 303 304 |
# File 'lib/prawn/document.rb', line 299 def go_to_page(k) @page_number = k jump_to = @store.pages.data[:Kids][k-1] @current_page = jump_to.identifier @page_content = jump_to.data[:Contents].identifier end |
#group(second_attempt = false) ⇒ Object
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).
Raises CannotGroup if the provided content is too large to fit alone in the current page or column.
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 |
# File 'lib/prawn/document.rb', line 497 def group(second_attempt=false) old_bounding_box = @bounding_box @bounding_box = SimpleDelegator.new(@bounding_box) def @bounding_box.move_past_bottom raise RollbackTransaction end success = transaction { yield } unless success raise CannotGroup if second_attempt old_bounding_box.move_past_bottom group(second_attempt=true) { yield } end @bounding_box = old_bounding_box end |
#indent(x, &block) ⇒ Object
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"
469 470 471 |
# File 'lib/prawn/document.rb', line 469 def indent(x, &block) bounds.indent(x, &block) end |
#mask(*fields) ⇒ Object
:nodoc:
474 475 476 477 478 479 480 481 482 |
# File 'lib/prawn/document.rb', line 474 def mask(*fields) # :nodoc: # Stores the current state of the named attributes, executes the block, and # then restores the original values after the block has executed. # -- I will remove the nodoc if/when this feature is a little less hacky stored = {} fields.each { |f| stored[f] = send(f) } yield fields.each { |f| send("#{f}=", stored[f]) } end |
#move_cursor_to(new_y) ⇒ Object
Moves to the specified y position in relative terms to the bottom margin.
321 322 323 |
# File 'lib/prawn/document.rb', line 321 def move_cursor_to(new_y) self.y = new_y + bounds.absolute_bottom end |
#move_down(n) ⇒ Object
Moves down the document by n points relative to the current position inside the current bounding box.
414 415 416 |
# File 'lib/prawn/document.rb', line 414 def move_down(n) self.y -= n end |
#move_up(n) ⇒ Object
Moves up the document by n points relative to the current position inside the current bounding box.
407 408 409 |
# File 'lib/prawn/document.rb', line 407 def move_up(n) self.y += n end |
#number_pages(string, position) ⇒ Object
Specify a template 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 doucment.
Example:
Prawn::Document.generate("page_with_numbering.pdf") do
text "Hai"
start_new_page
text "bai"
start_new_page
text "-- Hai again"
number_pages "<page> in a total of <total>", [bounds.right - 50, 0]
end
532 533 534 535 536 537 538 |
# File 'lib/prawn/document.rb', line 532 def number_pages(string, position) page_count.times do |i| go_to_page(i+1) str = string.gsub("<page>","#{i+1}").gsub("<total>","#{page_count}") text str, :at => position end end |
#pad(y) ⇒ Object
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"
453 454 455 456 457 |
# File 'lib/prawn/document.rb', line 453 def pad(y) move_down(y) yield move_down(y) end |
#pad_bottom(y) ⇒ Object
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"
439 440 441 442 |
# File 'lib/prawn/document.rb', line 439 def pad_bottom(y) yield move_down(y) end |
#pad_top(y) ⇒ Object
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"
426 427 428 429 |
# File 'lib/prawn/document.rb', line 426 def pad_top(y) move_down(y) yield end |
#page_count ⇒ Object
282 283 284 |
# File 'lib/prawn/document.rb', line 282 def page_count @store.pages.data[:Count] end |
#page_number ⇒ Object
Returns the 1-based page number of the current page. Returns 0 if the document has no pages.
289 290 291 |
# File 'lib/prawn/document.rb', line 289 def page_number @page_number end |
#render ⇒ Object
Renders the PDF document to string
342 343 344 345 346 347 348 349 350 351 352 353 |
# File 'lib/prawn/document.rb', line 342 def render output = StringIO.new finalize_all_page_contents render_header(output) render_body(output) render_xref(output) render_trailer(output) str = output.string str.force_encoding("ASCII-8BIT") if str.respond_to?(:force_encoding) str end |
#render_file(filename) ⇒ Object
Renders the PDF document to file.
pdf.render_file "foo.pdf"
359 360 361 362 |
# File 'lib/prawn/document.rb', line 359 def render_file(filename) Kernel.const_defined?("Encoding") ? mode = "wb:ASCII-8BIT" : mode = "wb" File.open(filename,mode) { |f| f << render } end |
#repeat(page_filter, &block) ⇒ Object
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
Example:
Prawn::Document.generate("repeat.pdf", :skip_page_creation => true) do
repeat :all do
text "ALLLLLL", :at => bounds.top_left
end
repeat :odd do
text "ODD", :at => [0,0]
end
repeat :even do
text "EVEN", :at => [0,0]
end
repeat [1,2] do
text "[1,2]", :at => [100,0]
end
repeat 2..4 do
text "2..4", :at => [200,0]
end
repeat(lambda { |pg| pg % 3 == 0 }) do
text "Every third", :at => [250, 20]
end
10.times do
start_new_page
text "A wonderful page", :at => [400,400]
end
end
69 70 71 |
# File 'lib/prawn/repeater.rb', line 69 def repeat(page_filter, &block) repeaters << Prawn::Repeater.new(self, page_filter, &block) end |
#repeaters ⇒ Object
A list of all repeaters in the document. See Document#repeat for details
18 19 20 |
# File 'lib/prawn/repeater.rb', line 18 def repeaters @repeaters ||= [] end |
#save_font ⇒ Object
Saves the current font, and then yields. When the block finishes, the original font is restored.
90 91 92 93 94 95 96 97 98 |
# File 'lib/prawn/font.rb', line 90 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 |
#set_font(font, size = nil) ⇒ Object
Sets the font directly, given an actual Font object and size.
82 83 84 85 |
# File 'lib/prawn/font.rb', line 82 def set_font(font, size=nil) # :nodoc: @font = font @font_size = size if size end |
#span(width, options = {}) ⇒ Object
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
27 28 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 |
# File 'lib/prawn/document/span.rb', line 27 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 raise 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 |
#start_new_page(options = {}) ⇒ Object
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)
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 |
# File 'lib/prawn/document.rb', line 245 def start_new_page( = {}) @page_size = [:size] if [:size] @page_layout = [:layout] if [:layout] apply_margin_option() if [:margin] [:left,:right,:top,:bottom].each do |side| if margin = [:"#{side}_margin"] @margins[side] = margin end end build_new_page_content @store.pages.data[:Kids].insert(@page_number, current_page) @store.pages.data[:Count] += 1 @page_number += 1 add_content "q" @y = @bounding_box.absolute_top image(@background, :at => [0,@y]) if @background float do @on_page_create_callback.call(self) if @on_page_create_callback end end |
#width_of(string, options = {}) ⇒ Object
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. ++
192 193 194 |
# File 'lib/prawn/font.rb', line 192 def width_of(string, ={}) font.compute_width_of(string, ) end |