Class: Prawn::Document
- Inherits:
-
Object
- Object
- Prawn::Document
- Includes:
- PDF::Core::Annotations, PDF::Core::Destinations, Security, Graphics, Images, SoftMask, Stamp, Text
- Defined in:
- lib/prawn/font.rb,
lib/prawn/grid.rb,
lib/prawn/outline.rb,
lib/prawn/document.rb,
lib/prawn/repeater.rb,
lib/prawn/security.rb,
lib/prawn/document/span.rb,
lib/prawn/document/internals.rb,
lib/prawn/document/column_box.rb,
lib/prawn/document/bounding_box.rb
Overview
rubocop: disable Style/Documentation
Defined Under Namespace
Modules: Security Classes: BoundingBox, ColumnBox, Grid, GridBox, MultiBox
Stable API collapse
- DEFAULT_OPTS =
Default empty options.
{}.freeze
Extension API collapse
- VALID_OPTIONS =
List of recognised options.
%i[ page_size page_layout margin left_margin right_margin top_margin bottom_margin skip_page_creation compress background info text_formatter print_scaling ].freeze
Stable Attributes collapse
-
#margin_box ⇒ Prawn::Document::BoundingBox
Current margin box.
-
#margins ⇒ {:left, :top, :right, :bottom => Number}
readonly
Current page margins.
-
#page_number ⇒ Integer
Current page number.
-
#y ⇒ Number
Absolute cursor position.
Extension Attributes collapse
-
#text_formatter ⇒ Object
Current text formatter.
Stable API collapse
-
.generate(filename, options = {}, &block) ⇒ Object
Creates and renders a PDF document.
-
#blend_mode(blend_mode = :Normal) { ... } ⇒ void
included
from Graphics::BlendMode
Set blend mode.
-
#bounding_box(point, options = {}) {|parent_box| ... } ⇒ void
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.
-
#bounds ⇒ Prawn::Document::BoundingBox
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) ⇒ bounding_box
Sets #bounds to the BoundingBox provided.
-
#canvas(&block) ⇒ void
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.
-
#cap_style(style) ⇒ void
#cap_style ⇒ Symbol
(also: #cap_style=)
included
from Graphics::CapStyle
Sets the cap style for stroked lines and curves.
-
#circle(center, radius) ⇒ void
included
from Graphics
Draws a circle of radius
radius
with the centre-point atpoint
as a complete subpath. -
#close_and_stroke { ... } ⇒ void
included
from Graphics
Closes and strokes the current path.
-
#close_path ⇒ Object
included
from Graphics
Closes the current path.
-
#create_stamp(name) { ... } ⇒ void
included
from Stamp
Creates a re-usable stamp.
-
#cursor ⇒ Number
The current y drawing position relative to the innermost bounding box, or to the page margins at the top level.
-
#curve(origin, dest, options = {}) ⇒ void
included
from Graphics
Draws a Bezier curve between two points, bounded by two additional points.
-
#curve_to(dest, options = {}) ⇒ void
included
from Graphics
Draws a Bezier curve from the current drawing position to the specified point, bounded by two additional points.
-
#dash ⇒ Hash{:dash => Number, Array<Number>, :space => Number, nil, :phase => Number}
#dash(length, options = {}) ⇒ void
(also: #dash=)
included
from Graphics::Dash
Get or set stroke dash pattern.
-
#dashed? ⇒ Boolean
included
from Graphics::Dash
Returns
true
when stroke is dashed,false
otherwise. -
#delete_page(index) ⇒ Boolean
Remove page of the document by index.
-
#draw_text(text, options) ⇒ void
included
from Text
Draws text on the page, beginning at the point specified by the
:at
option the string is assumed to be pre-formatted to properly fit the page. -
#draw_text!(text, options) ⇒ void
included
from Text
Low level text placement method.
-
#ellipse(point, radius1, radius2 = radius1) ⇒ void
included
from Graphics
Draws an ellipse of
x
radiusradius1
andy
radiusradius2
with the centre-point atpoint
as a complete subpath. -
#fill(options = {}) { ... } ⇒ void
included
from Graphics
Closes and fills the current path.
-
#fill_and_stroke(options = {}) { ... } ⇒ void
included
from Graphics
Closes, fills, and strokes the current path.
-
#fill_and_stroke_circle(center, radius) ⇒ void
included
from Graphics
Draws, strokes, and fills a circle of radius
radius
with the centre-point atpoint
. -
#fill_and_stroke_ellipse(point, radius1, radius2 = radius1) ⇒ void
included
from Graphics
Draws, strokes, and fills an ellipse of x radius
r1
and y radiusr2
with the centre-point atpoint
. -
#fill_and_stroke_polygon(*points) ⇒ void
included
from Graphics
Draws, strokes, and fills a polygon from the specified points.
-
#fill_and_stroke_rectangle(point, width, height) ⇒ void
included
from Graphics
Draws, fills, and strokes a rectangle given
point
,width
, andheight
. -
#fill_and_stroke_rounded_rectangle(point, width, height, radius) ⇒ void
included
from Graphics
Draws, fills, and strokes a rounded rectangle given
point
,width
, andheight
andradius
for the rounded corner. -
#fill_circle(center, radius) ⇒ void
included
from Graphics
Draws and fills a circle of radius
radius
with the centre-point atpoint
. -
#fill_color ⇒ String, Array<Number>
#fill_color(color) ⇒ void
(also: #fill_color=)
included
from Graphics::Color
Sets or returns the fill color.
-
#fill_ellipse(point, radius1, radius2 = radius1) ⇒ void
included
from Graphics
Draws and fills an ellipse of x radius
r1
and y radiusr2
with the centre-point atpoint
. -
#fill_gradient(from, to, color1, color2, apply_margin_options: false) ⇒ void
#fill_gradient(from, r1, to, r2, color1, color2, apply_margin_options: false) ⇒ void
#fill_gradient(from: , to: , r1: nil, r2: nil, stops: , apply_margin_options: true) ⇒ void
included
from Graphics::Patterns
Sets the fill gradient.
-
#fill_polygon(*points) ⇒ void
included
from Graphics
Draws and fills a polygon from the specified points.
-
#fill_rectangle(point, width, height) ⇒ void
included
from Graphics
Draws and fills a rectangle given
point
,width
, andheight
. -
#fill_rounded_polygon(radius, *points) ⇒ void
included
from Graphics
Draws and fills a rounded polygon from specified points, using
radius
to define Bezier curves. -
#fill_rounded_rectangle(point, width, height, radius) ⇒ void
included
from Graphics
Draws and fills a rounded rectangle given
point
,width
andheight
, andradius
for the rounded corner. -
#float ⇒ void
Executes a block and then restores the original y position.
-
#font(name = nil, options = DEFAULT_OPTS) { ... } ⇒ Font
Without arguments, this returns the currently selected font.
-
#font_families ⇒ Hash{String => Hash{Symbol => String, Hash{Symbol => String}}}
Hash that maps font family names to their styled individual font definitions.
-
#font_size ⇒ Number
#font_size(points) { ... } ⇒ void
When called with no argument, returns the current font size.
-
#font_size=(size) ⇒ Number
Sets the font size.
-
#formatted_text(array, options = {}) ⇒ void
included
from Text
Draws formatted text to the page.
-
#formatted_text_box(array, options = {}) ⇒ Array<Hash>
included
from Text::Formatted
Draws the requested formatted text into a box.
-
#go_to_page(page_number) ⇒ void
Re-opens the page with the given (1-based) page number so that you can draw on it.
-
#height_of(string, options = {}) ⇒ void
included
from Text
Gets height of text in PDF points.
-
#height_of_formatted(array, options = {}) ⇒ void
included
from Text
Gets height of formatted text in PDF points.
-
#horizontal_line(x1, x2, options = {}) ⇒ void
included
from Graphics
Draws a horizontal line from
x1
tox2
at the current #y position, or the position specified by the:at
option. -
#horizontal_rule ⇒ void
included
from Graphics
Draws a horizontal line from the left border to the right border of the bounding box at the current #y position.
-
#image(file, options = {}) ⇒ Prawn::Images::Image
included
from Images
Add the image at
file
to the current page. -
#indent(left, right = 0) { ... } ⇒ void
Indents the specified number of PDF points for the duration of the block.
-
#initialize(options = {}, &block) ⇒ Document
constructor
Creates a new PDF Document.
-
#join_style ⇒ :miter, ...
#join_style(style) ⇒ void
(also: #join_style=)
included
from Graphics::JoinStyle
Get or set the join style for stroked lines and curves.
-
#line(point1, point2) ⇒ void
#line(x1, y1, x2, y2) ⇒ void
included
from Graphics
Draws a line from one point to another.
-
#line_to(point) ⇒ void
#line_to(x, y) ⇒ void
included
from Graphics
Draws a line from the current drawing position to the specified point.
-
#line_width ⇒ Number
#line_width(width) ⇒ void
included
from Graphics
When called without an argument, returns the current line thickness.
-
#line_width=(width) ⇒ void
included
from Graphics
Sets line thickness to the
width
specified. -
#move_cursor_to(new_y) ⇒ void
Moves to the specified y position in relative terms to the bottom margin.
-
#move_down(amount) ⇒ void
Moves down the document by n points relative to the current position inside the current bounding box.
-
#move_to(point) ⇒ void
#move_to(x, y) ⇒ void
included
from Graphics
Moves the drawing position to a given point.
-
#move_up(amount) ⇒ void
Moves up the document by n points relative to the current position inside the current bounding box.
-
#number_pages(string, options = {}) ⇒ Object
Places a text box on specified pages for page numbering.
-
#outline ⇒ Prawn::Outline
Lazily instantiates a Prawn::Outline object for document.
-
#pad(y) { ... } ⇒ void
Moves down the document by y, executes a block, then moves down the document by y again.
-
#pad_bottom(y) { ... } ⇒ void
Executes a block then moves down the document.
-
#pad_top(y) { ... } ⇒ void
Moves down the document and then executes a block.
-
#page_count ⇒ Integer
Number of pages in the document.
-
#polygon(*points) ⇒ void
included
from Graphics
Draws a polygon from the specified points.
-
#rectangle(point, width, height) ⇒ void
included
from Graphics
Draws a rectangle given
point
,width and
height`. -
#render(output = nil) ⇒ String
Renders the PDF document to string.
-
#render_file(filename) ⇒ void
Renders the PDF document to file.
-
#rotate(angle, options = {}) { ... } ⇒ void
included
from Graphics::Transformation
Rotate the user space.
-
#rounded_polygon(radius, *points) ⇒ void
included
from Graphics
Draws a rounded polygon from specified points using the radius to define bezier curves.
-
#rounded_rectangle(point, width, height, radius) ⇒ void
included
from Graphics
Draws a rounded rectangle given
point
,width
,height
, andradius
for the rounded corner. -
#rounded_vertex(radius, *points) ⇒ void
included
from Graphics
Creates a rounded vertex for a line segment used for building a rounded polygon requires a radius to define bezier curve and three points.
-
#scale(factor, options = {}) { ... } ⇒ void
included
from Graphics::Transformation
Scale the user space.
-
#soft_mask { ... } ⇒ void
included
from SoftMask
Apply soft mask.
-
#span(width, options = {}) { ... } ⇒ void
A span is a special purpose bounding box that allows a column of elements to be positioned relative to the margin_box.
-
#stamp(name) ⇒ void
included
from Stamp
Renders the stamp.
-
#stamp_at(name, point) ⇒ void
included
from Stamp
Renders the stamp at a position offset from the initial coords at which the elements of the stamp was created.
-
#start_new_page(options = {}) ⇒ void
Creates and advances to a new page in the document.
-
#stroke { ... } ⇒ void
included
from Graphics
Strokes the current path.
-
#stroke_axis(options = {}) ⇒ void
included
from Graphics
Draws and strokes X and Y axes rulers beginning at the current bounding box origin (or at a custom location).
-
#stroke_bounds ⇒ void
included
from Graphics
Draws and strokes a rectangle represented by the current bounding box.
-
#stroke_color ⇒ String, Array<Number>
#stroke_color(color) ⇒ void
(also: #stroke_color=)
included
from Graphics::Color
Sets or returns the line stroking color.
-
#stroke_curve(origin, dest, options = {}) ⇒ void
included
from Graphics
Strokes a Bezier curve between two points, bounded by two additional points.
-
#stroke_ellipse(point, radius1, radius2 = radius1) ⇒ void
included
from Graphics
Draws and strokes an ellipse of x radius
r1
and y radiusr2
with the centre-point atpoint
. -
#fill_gradient(from, to, color1, color2, apply_margin_options: false) ⇒ void
#fill_gradient(from, r1, to, r2, color1, color2, apply_margin_options: false) ⇒ void
#fill_gradient(from: , to: , r1: nil, r2: nil, stops: , apply_margin_options: true) ⇒ void
included
from Graphics::Patterns
Sets the stroke gradient.
-
#stroke_horizontal_line(x1, x2, options = {}) ⇒ void
included
from Graphics
Strokes a horizontal line from
x1
tox2
at the current y position, or the position specified by the :at option. -
#stroke_horizontal_rule ⇒ void
included
from Graphics
Strokes a horizontal line from the left border to the right border of the bounding box at the current y position.
-
#line(point1, point2) ⇒ void
#line(x1, y1, x2, y2) ⇒ void
included
from Graphics
Strokes a line from one point to another.
-
#stroke_polygon(*points) ⇒ Object
included
from Graphics
Draws and strokes a polygon from the specified points.
-
#stroke_rectangle(point, width, height) ⇒ void
included
from Graphics
Draws and strokes a rectangle given
point
,width
, andheight
. -
#stroke_rounded_polygon(radius, *points) ⇒ void
included
from Graphics
Draws and strokes a rounded polygon from specified points, using
radius
to define Bezier curves. -
#stroke_rounded_rectangle(point, width, height, radius) ⇒ void
included
from Graphics
Draws and strokes a rounded rectangle given
point
,width
andheight
, andradius
for the rounded corner. -
#stroke_vertical_line(y1, y2, params) ⇒ void
included
from Graphics
Strokes a vertical line at the x coordinate given by
:at
fromy1
toy2
. -
#text(string, options = {}) ⇒ void
included
from Text
Draws text on the page.
-
#text_box(string, options = {}) ⇒ String
included
from Text
Draws the requested text into a box.
-
#transformation_matrix(*matrix) { ... } ⇒ void
included
from Graphics::Transformation
Transform the user space (see notes for rotate regarding graphics state) Generally, one would use the Graphics::Transformation#rotate, Graphics::Transformation#scale, and Graphics::Transformation#translate convenience methods instead of calling transformation_matrix directly.
-
#translate(x, y) { ... } ⇒ void
included
from Graphics::Transformation
Translate the user space.
-
#transparent(opacity, stroke_opacity = opacity) { ... } ⇒ void
included
from Graphics::Transparency
Set opacity.
-
#undash ⇒ void
included
from Graphics::Dash
Stops dashing, restoring solid stroked lines and curves.
-
#vertical_line(y1, y2, params) ⇒ void
included
from Graphics
Draws a vertical line at the x coordinate given by
:at
fromy1
toy2
. -
#width_of(string, options = {}) ⇒ Number
Returns the width of the given string using the given font.
Experimental API collapse
-
#column_box(point, options = {}) {|parent_box| ... } ⇒ void
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.
-
#define_grid(options = {}) ⇒ Grid
Defines the grid system for a particular document.
-
#encrypt_document(options = {}) ⇒ void
included
from Security
Encrypts the document, to protect confidential data or control modifications to the document.
-
#grid ⇒ Grid
#grid(row, column) ⇒ GridBox
#grid(box1, box2) ⇒ MultiBox
A method that can either be used to access a particular grid on the page or work with the grid system directly.
-
#page_match?(page_filter, page_number) ⇒ Boolean
Provides a way to execute a block of code repeatedly based on a page_filter.
-
#repeat(page_filter, options = {}, &block) ⇒ void
Provides a way to execute a block of code repeatedly based on a
page_filter
. -
#save_font { ... } ⇒ void
Saves the current font, and then yields.
Extension API collapse
-
.extensions ⇒ Array<Module>
Any module added to this array will be included into instances of Document at the per-object level.
-
#initialize_first_page(options) ⇒ void
Initializes the first page in a new document.
Constructor Details
#initialize(options = {}, &block) ⇒ Document
Creates a new PDF Document.
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.
Source Code
227 | def initialize(options = {}, &block) |
228 | options = options.dup |
229 | |
230 | Prawn.verify_options(VALID_OPTIONS, options) |
231 | |
232 | # need to fix, as the refactoring breaks this
|
233 | # raise NotImplementedError if options[:skip_page_creation]
|
234 | |
235 | self.class.extensions.reverse_each { |e| extend(e) } |
236 | self.state = PDF::Core::DocumentState.new(options) |
237 | state.populate_pages_from_store(self) |
238 | renderer.min_version(state.store.min_version) if state.store.min_version |
239 | |
240 | renderer.min_version(1.6) if options[:print_scaling] == :none |
241 | |
242 | @background = options[:background] |
243 | @background_scale = options[:background_scale] || 1 |
244 | @font_size = 12 |
245 | |
246 | @bounding_box = nil |
247 | @margin_box = nil |
248 | |
249 | @page_number = 0 |
250 | |
251 | @text_formatter = options.delete(:text_formatter) || |
252 | Text::Formatted::Parser |
253 | |
254 | options[:size] = options.delete(:page_size) |
255 | options[:layout] = options.delete(:page_layout) |
256 | |
257 | initialize_first_page(options) |
258 | |
259 | @bounding_box = @margin_box |
260 | |
261 | if block |
262 | block.arity < 1 ? instance_eval(&block) : block[self] |
263 | end
|
264 | end
|
Instance Attribute Details
#margin_box ⇒ Prawn::Document::BoundingBox
Current margin box.
Source Code
109 | def margin_box |
110 | @margin_box
|
111 | end
|
#margins ⇒ {:left, :top, :right, :bottom => Number} (readonly)
Current page margins.
Source Code
113 | def margins |
114 | @margins
|
115 | end
|
#page_number ⇒ Integer
Current page number.
Source Code
121 | def page_number |
122 | @page_number
|
123 | end
|
#text_formatter ⇒ Object
Current text formatter. By default it’s Text::Formatted::Parser
Source Code
127 | def text_formatter |
128 | @text_formatter
|
129 | end
|
#y ⇒ Number
Absolute cursor position.
Source Code
117 | def y |
118 | @y
|
119 | end
|
Class Method Details
.extensions ⇒ Array<Module>
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.
Source Code
95 | def self.extensions |
96 | @extensions ||= [] |
97 | 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"
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 Prawn::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
Source Code
161 | def self.generate(filename, options = {}, &block) |
162 | pdf = new(options, &block) |
163 | pdf.render_file(filename) |
164 | end
|
Instance Method Details
#blend_mode(blend_mode = :Normal) { ... } ⇒ void Originally defined in module Graphics::BlendMode
This method returns an undefined value.
Set blend mode. If a block is passed blend mode is restored afterwards.
Passing an array of blend modes is allowed. PDF viewers should blend layers based on the first recognized blend mode.
Valid blend modes since PDF 1.4 include :Normal
, :Multiply
, :Screen
,
:Overlay
, :Darken
, :Lighten
, :ColorDodge
, :ColorBurn
,
:HardLight
, :SoftLight
, :Difference
, :Exclusion
, :Hue
,
:Saturation
, :Color
, and :Luminosity
.
#bounding_box(point, options = {}) {|parent_box| ... } ⇒ void
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×100pt in the absolute bottom left of the containing box:
pdf.bounding_box([0, 100], width: 100, height: 100) stroke_bounds end
-
Bounding box 200pt×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#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
Stretchiness
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 #Prawn::Document.pdfpdf.boundspdf.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 #Prawn::Document.pdfpdf.boundspdf.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.
Source Code
174 | def bounding_box(point, *args, &block) |
175 | init_bounding_box(block) do |parent_box| |
176 | point = map_to_absolute(point) |
177 | @bounding_box = BoundingBox.new(self, parent_box, point, *args) |
178 | end
|
179 | end
|
#bounds ⇒ Prawn::Document::BoundingBox
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.
Source Code
504 | def bounds |
505 | @bounding_box
|
506 | end
|
#bounds=(bounding_box) ⇒ bounding_box
Sets #bounds to the BoundingBox provided. See #bounds 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.
Source Code
523 | def bounds=(bounding_box) |
524 | @bounding_box = bounding_box |
525 | end
|
#canvas(&block) ⇒ void
This method returns an undefined value.
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.
Source Code
191 | def canvas(&block) |
192 | init_bounding_box(block, hold_position: true) do |_| |
193 | # Canvas bbox acts like margin_box in that its parent bounds are unset.
|
194 | @bounding_box = BoundingBox.new( |
195 | self, |
196 | nil, |
197 | [0, page.dimensions[3]], |
198 | width: page.dimensions[2], |
199 | height: page.dimensions[3], |
200 | )
|
201 | end
|
202 | end
|
#cap_style(style) ⇒ void #cap_style ⇒ Symbol Also known as: cap_style= Originally defined in module Graphics::CapStyle
Sets the cap style for stroked lines and curves.
#circle(center, radius) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a circle of radius radius
with the centre-point at
point
as a complete subpath. The drawing point will be moved to
the centre-point upon completion of the drawing the circle.
#close_and_stroke { ... } ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Closes and strokes the current path. If a block is provided, yields to the block before closing the path. See Color for color details.
#close_path ⇒ Object Originally defined in module Graphics
Closes the current path.
#column_box(point, options = {}) {|parent_box| ... } ⇒ void
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.
Source Code
34 | def column_box(*args, &block) |
35 | init_column_box(block) do |parent_box| |
36 | map_to_absolute!(args[0]) |
37 | @bounding_box = ColumnBox.new(self, parent_box, *args) |
38 | end
|
39 | end
|
#create_stamp(name) { ... } ⇒ void Originally defined in module Stamp
This method returns an undefined value.
Creates a re-usable stamp.
#cursor ⇒ Number
The current y drawing position relative to the innermost bounding box, or to the page margins at the top level.
Source Code
415 | def cursor |
416 | y - bounds.absolute_bottom |
417 | end
|
#curve(origin, dest, options = {}) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a Bezier curve between two points, bounded by two additional points
#curve_to(dest, options = {}) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a Bezier curve from the current drawing position to the specified point, bounded by two additional points.
#dash ⇒ Hash{:dash => Number, Array<Number>, :space => Number, nil, :phase => Number} #dash(length, options = {}) ⇒ void Also known as: dash= Originally defined in module Graphics::Dash
Get or set stroke dash pattern.
#dashed? ⇒ Boolean Originally defined in module Graphics::Dash
Returns true
when stroke is dashed, false
otherwise.
#define_grid(options = {}) ⇒ Grid
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.
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
Source Code
24 | def define_grid(options = {}) |
25 | @boxes = nil |
26 | @grid = Grid.new(self, options) |
27 | end
|
#delete_page(index) ⇒ Boolean
Remove page of the document by index.
Source Code
366 | def delete_page(index) |
367 | return false if index.abs > (state.pages.count - 1) |
368 | |
369 | state.pages.delete_at(index) |
370 | |
371 | state.store.pages.data[:Kids].delete_at(index) |
372 | state.store.pages.data[:Count] -= 1 |
373 | @page_number -= 1 |
374 | true
|
375 | end
|
#draw_text(text, options) ⇒ void Originally defined in module Text
This method returns an undefined value.
Draws text on the page, beginning at the point specified by the :at
option the string is assumed to be pre-formatted to properly fit the page.
pdf.draw_text "Hello World", at: [100, 100]
pdf.draw_text "Goodbye World", at: [50,50], size: 16
If your font contains kerning pair data that Prawn can parse, the
text will be kerned by default. You can disable kerning by including
a false
:kerning
option. If you want to disable kerning on an
entire document, set default_kerning = false
for that document
Text Positioning Details
Prawn will position your text by the left-most edge of its baseline, and
flow along a single line. (This means that :align
will not work)
Rotation
Text can be rotated before it is placed on the canvas by specifying the
:rotate
option with a given angle. Rotation occurs counter-clockwise.
Encoding
Note that strings passed to this function should be encoded as UTF-8. If you get unexpected characters appearing in your rendered document, check this.
If the current font is a built-in one, although the string must be encoded as UTF-8, only characters that are available in WinAnsi are allowed.
If an empty box is rendered to your PDF instead of the character you wanted it usually means the current font doesn’t include that character.
#draw_text!(text, options) ⇒ void Originally defined in module Text
This method returns an undefined value.
Low level text placement method.
All font and size alterations should already be set.
#ellipse(point, radius1, radius2 = radius1) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws an ellipse of x
radius radius1
and y
radius radius2
with the
centre-point at point
as a complete subpath. The drawing point will be
moved to the centre-point upon completion of the drawing the ellipse.
#encrypt_document(options = {}) ⇒ void Originally defined in module Security
This method returns an undefined value.
Encrypts the document, to protect confidential data or control modifications to the document. The encryption algorithm used is detailed in the PDF Reference 1.3, section 3.5 “Encryption”, and it is implemented by all major PDF readers.
Examples
Deny printing to everyone, but allow anyone to open without a password:
encrypt_document permissions: { print_document: false },
owner_password: :random
Set a user and owner password on the document, with full permissions for both the user and the owner:
encrypt_document user_password: 'foo', owner_password: 'bar'
Set no passwords, grant all permissions (This is useful because the default in some readers, if no permissions are specified, is “deny”):
encrypt_document
Caveats
- The encryption used is weak; the key is password-derived and is limited to 40 bits, due to US export controls in effect at the time the PDF standard was written.
- There is nothing technologically requiring PDF readers to respect the permissions embedded in a document. Many PDF readers do not.
- In short, you have no security at all against a moderately motivated person. Don’t use this for anything super-serious. This is not a limitation of Prawn, but is rather a built-in limitation of the PDF format.
#fill(options = {}) { ... } ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Closes and fills the current path. See Color for color details.
If the option fill_rule: :even_odd
is specified, Prawn will use the
even-odd rule to fill the path. Otherwise, the nonzero winding number rule
will be used. See the PDF reference, “Graphics -> Path Construction and
Painting -> Clipping Path Operators” for details on the difference.
#fill_and_stroke(options = {}) { ... } ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Closes, fills, and strokes the current path. If a block is provided, yields to the block before closing the path. See Color for color details.
If the option fill_rule: :even_odd
is specified, Prawn will use the
even-odd rule to fill the path. Otherwise, the nonzero winding number rule
will be used. See the PDF reference, “Graphics -> Path Construction and
Painting -> Clipping Path Operators” for details on the difference.
#fill_and_stroke_circle(center, radius) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws, strokes, and fills a circle of radius radius
with the
centre-point at point
.
#fill_and_stroke_ellipse(point, radius1, radius2 = radius1) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws, strokes, and fills an ellipse of x radius r1
and y radius r2
with the centre-point at point
.
#fill_and_stroke_polygon(*points) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws, strokes, and fills a polygon from the specified points.
#fill_and_stroke_rectangle(point, width, height) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws, fills, and strokes a rectangle given point
, width
, and
height
. The rectangle is bounded by its upper-left corner.
#fill_and_stroke_rounded_rectangle(point, width, height, radius) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws, fills, and strokes a rounded rectangle given point
, width
,
and height
and radius
for the rounded corner. The rectangle is
bounded by its upper-left corner.
#fill_circle(center, radius) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and fills a circle of radius radius
with the centre-point at
point
.
#fill_color ⇒ String, Array<Number> #fill_color(color) ⇒ void Also known as: fill_color= Originally defined in module Graphics::Color
Sets or returns the fill color.
#fill_ellipse(point, radius1, radius2 = radius1) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and fills an ellipse of x radius r1
and y radius r2
with the
centre-point at point
.
#fill_gradient(from, to, color1, color2, apply_margin_options: false) ⇒ void #fill_gradient(from, r1, to, r2, color1, color2, apply_margin_options: false) ⇒ void #fill_gradient(from: , to: , r1: nil, r2: nil, stops: , apply_margin_options: true) ⇒ void Originally defined in module Graphics::Patterns
Sets the fill gradient.
#fill_polygon(*points) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and fills a polygon from the specified points.
#fill_rectangle(point, width, height) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and fills a rectangle given point
, width
, and height
. The
rectangle is bounded by its upper-left corner.
#fill_rounded_polygon(radius, *points) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and fills a rounded polygon from specified points, using radius
to define Bezier curves.
#fill_rounded_rectangle(point, width, height, radius) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and fills a rounded rectangle given point
, width
and height
,
and radius
for the rounded corner. The rectangle is bounded by its
upper-left corner.
#float ⇒ void
This method returns an undefined value.
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.
Source Code
442 | def float |
443 | original_page = page_number |
444 | original_y = y |
445 | yield
|
446 | go_to_page(original_page) unless page_number == original_page |
447 | self.y = original_y |
448 | end
|
#font(name = nil, options = DEFAULT_OPTS) { ... } ⇒ Font
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
Fonts::AFM::BUILT_INS array specifies the valid built in font names.
If a TTF/OTF 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.
Source Code
56 | def font(name = nil, options = DEFAULT_OPTS) |
57 | return((defined?(@font) && @font) || font('Helvetica')) if name.nil? |
58 | |
59 | if state.pages.empty? && !state.page.in_stamp_stream? |
60 | raise Prawn::Errors::NotOnPage |
61 | end
|
62 | |
63 | new_font = find_font(name.to_s, options) |
64 | |
65 | if block_given? |
66 | save_font do |
67 | set_font(new_font, options[:size]) |
68 | yield
|
69 | end
|
70 | else
|
71 | set_font(new_font, options[:size]) |
72 | end
|
73 | |
74 | @font
|
75 | end
|
#font_families ⇒ Hash{String => Hash{Symbol => String, Hash{Symbol => String}}}
Hash that maps font family names to their styled individual font definitions.
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/OTF 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.
Font definition can be either a hash or just a string.
A hash font definition can specify a number of options:
:file
– path to the font file (required):subset
– whether to subset the font (default false). Only applicable to TrueType and OpenType fonts (includnig DFont and TTC).
A string font definition is equivalent to hash definition with only
:file
being specified.
Source Code
212 | def font_families |
213 | @font_families ||= {}.merge!( |
214 | 'Courier' => { |
215 | bold: 'Courier-Bold', |
216 | italic: 'Courier-Oblique', |
217 | bold_italic: 'Courier-BoldOblique', |
218 | normal: 'Courier', |
219 | },
|
220 | |
221 | 'Times-Roman' => { |
222 | bold: 'Times-Bold', |
223 | italic: 'Times-Italic', |
224 | bold_italic: 'Times-BoldItalic', |
225 | normal: 'Times-Roman', |
226 | },
|
227 | |
228 | 'Helvetica' => { |
229 | bold: 'Helvetica-Bold', |
230 | italic: 'Helvetica-Oblique', |
231 | bold_italic: 'Helvetica-BoldOblique', |
232 | normal: 'Helvetica', |
233 | },
|
234 | )
|
235 | end
|
#font_size ⇒ Number #font_size(points) { ... } ⇒ void
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
.
Source Code
106 | def font_size(points = nil) |
107 | return @font_size unless points |
108 | |
109 | size_before_yield = @font_size |
110 | @font_size = points |
111 | block_given? ? yield : return |
112 | @font_size = size_before_yield |
113 | end
|
#font_size=(size) ⇒ Number
Sets the font size.
Source Code
119 | def font_size=(size) |
120 | font_size(size) |
121 | end
|
#formatted_text(array, options = {}) ⇒ void Originally defined in module Text
This method returns an undefined value.
Draws formatted text to the page.
Formatted text is an array of hashes, where each hash defines text and format information.
#formatted_text_box(array, options = {}) ⇒ Array<Hash> Originally defined in module Text::Formatted
Draws the requested formatted text into a box.
When the text overflows the rectangle shrink to fit or truncate the text. Text boxes are independent of the document y position.
#go_to_page(page_number) ⇒ void
This method returns an undefined value.
Re-opens the page with the given (1-based) page number so that you can draw on it.
Source Code
395 | def go_to_page(page_number) |
396 | @page_number = page_number |
397 | state.page = state.pages[page_number - 1] |
398 | generate_margin_box
|
399 | @y = @bounding_box.absolute_top |
400 | end
|
#grid ⇒ Grid #grid(row, column) ⇒ GridBox #grid(box1, box2) ⇒ MultiBox
A method that can either be used to access a particular grid on the page or work with the grid system directly.
Source Code
50 | def grid(*args) |
51 | @boxes ||= {} |
52 | @boxes[args] ||= |
53 | if args.empty? |
54 | @grid
|
55 | else
|
56 | g1, g2 = args |
57 | |
58 | if g1.is_a?(Array) && g2.is_a?(Array) && |
59 | g1.length == 2 && g2.length == 2 |
60 | multi_box(single_box(*g1), single_box(*g2)) |
61 | else
|
62 | single_box(g1, g2) |
63 | end
|
64 | end
|
65 | end
|
#height_of(string, options = {}) ⇒ void Originally defined in module Text
This method takes the same options as #text, except
:indent_paragraphs
.
This method returns an undefined value.
Gets height of text in PDF points.
#height_of_formatted(array, options = {}) ⇒ void Originally defined in module Text
This method takes the same options as #text, except
:indent_paragraphs
.
This method returns an undefined value.
Gets height of formatted text in PDF points.
#horizontal_line(x1, x2, options = {}) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a horizontal line from x1
to x2
at the current Document#y
position, or the position specified by the :at
option.
#horizontal_rule ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a horizontal line from the left border to the right border of the bounding box at the current Document#y position.
#image(file, options = {}) ⇒ Prawn::Images::Image Originally defined in module Images
Add the image at file
to the current page. Currently only JPG and
PNG files are supported. (Note that processing PNG images with alpha
channels can be processor and memory intensive.)
If only one of :width
or :height
are provided, the image will be
scaled proportionally. When both are provided, the image will be stretched
to fit the dimensions without maintaining the aspect ratio.
#indent(left, right = 0) { ... } ⇒ void
This method returns an undefined value.
Indents the specified number of PDF points for the duration of the block
Source Code
615 | def indent(left, right = 0, &block) |
616 | bounds.indent(left, right, &block) |
617 | end
|
#initialize_first_page(options) ⇒ void
This method returns an undefined value.
Initializes the first page in a new document. This methods allows customisation of this process in extensions such as Prawn::Template.
Source Code
767 | def initialize_first_page(options) |
768 | if options[:skip_page_creation] |
769 | start_new_page(options.merge(orphan: true)) |
770 | else
|
771 | start_new_page(options) |
772 | end
|
773 | end
|
#join_style ⇒ :miter, ... #join_style(style) ⇒ void Also known as: join_style= Originally defined in module Graphics::JoinStyle
Get or set the join style for stroked lines and curves.
#line(point1, point2) ⇒ void #line(x1, y1, x2, y2) ⇒ void Originally defined in module Graphics
Draws a line from one point to another. Points may be specified as tuples or flattened argument list.
#line_to(point) ⇒ void #line_to(x, y) ⇒ void Originally defined in module Graphics
Draws a line from the current drawing position to the specified point. The destination may be described as a tuple or a flattened list:
#line_width ⇒ Number #line_width(width) ⇒ void Originally defined in module Graphics
When called without an argument, returns the current line thickness. When called with an argument, sets the line thickness to the specified value (in PDF points).
#line_width=(width) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Sets line thickness to the width
specified.
#move_cursor_to(new_y) ⇒ void
This method returns an undefined value.
Moves to the specified y position in relative terms to the bottom margin.
Source Code
423 | def move_cursor_to(new_y) |
424 | self.y = new_y + bounds.absolute_bottom |
425 | end
|
#move_down(amount) ⇒ void
This method returns an undefined value.
Moves down the document by n points relative to the current position inside the current bounding box.
Source Code
541 | def move_down(amount) |
542 | self.y -= amount |
543 | end
|
#move_to(point) ⇒ void #move_to(x, y) ⇒ void Originally defined in module Graphics
Moves the drawing position to a given point. The point can be specified as a tuple or a flattened argument list.
#move_up(amount) ⇒ void
This method returns an undefined value.
Moves up the document by n points relative to the current position inside the current bounding box.
Source Code
532 | def move_up(amount) |
533 | self.y += amount |
534 | end
|
#number_pages(string, options = {}) ⇒ Object
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 generate
block because the method iterates through existing pages after they are
created.
Please refer to Text#text_box for additional options concerning text formatting and placement.
Source Code
652 | def number_pages(string, options = {}) |
653 | opts = options.dup |
654 | start_count_at = opts.delete(:start_count_at) |
655 | |
656 | page_filter = |
657 | if opts.key?(:page_filter) |
658 | opts.delete(:page_filter) |
659 | else
|
660 | :all
|
661 | end
|
662 | |
663 | total_pages = opts.delete(:total_pages) |
664 | txtcolor = opts.delete(:color) |
665 | # An explicit height so that we can draw page numbers in the margins
|
666 | opts[:height] = 50 unless opts.key?(:height) |
667 | |
668 | start_count = false |
669 | pseudopage = 0 |
670 | (1..page_count).each do |p| |
671 | unless start_count |
672 | pseudopage = |
673 | case start_count_at |
674 | when String |
675 | Integer(start_count_at, 10) |
676 | when (1..) |
677 | Integer(start_count_at) |
678 | else
|
679 | 1
|
680 | end
|
681 | end
|
682 | if page_match?(page_filter, p) |
683 | go_to_page(p) |
684 | # have to use fill_color here otherwise text reverts back to default
|
685 | # fill color
|
686 | fill_color(txtcolor) unless txtcolor.nil? |
687 | total_pages = page_count if total_pages.nil? |
688 | str = string.gsub('<page>', pseudopage.to_s) |
689 | .gsub('<total>', total_pages.to_s) |
690 | text_box(str, opts) |
691 | start_count = true # increment page count as soon as first match found |
692 | end
|
693 | pseudopage += 1 if start_count |
694 | end
|
695 | end
|
#outline ⇒ Prawn::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.
Source Code
12 | def outline |
13 | @outline ||= Outline.new(self) |
14 | end
|
#pad(y) { ... } ⇒ void
This method returns an undefined value.
Moves down the document by y, executes a block, then moves down the document by y again.
Source Code
592 | def pad(y) |
593 | move_down(y) |
594 | yield
|
595 | move_down(y) |
596 | end
|
#pad_bottom(y) { ... } ⇒ void
This method returns an undefined value.
Executes a block then moves down the document
Source Code
574 | def pad_bottom(y) |
575 | yield
|
576 | move_down(y) |
577 | end
|
#pad_top(y) { ... } ⇒ void
This method returns an undefined value.
Moves down the document and then executes a block.
Source Code
557 | def pad_top(y) |
558 | move_down(y) |
559 | yield
|
560 | end
|
#page_count ⇒ Integer
Number of pages in the document.
Source Code
386 | def page_count |
387 | state.page_count |
388 | end
|
#page_match?(page_filter, page_number) ⇒ Boolean
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
Source Code
733 | def page_match?(page_filter, page_number) |
734 | case page_filter |
735 | when :all |
736 | true
|
737 | when :odd |
738 | page_number.odd? |
739 | when :even |
740 | page_number.even? |
741 | when Range, Array |
742 | page_filter.include?(page_number) |
743 | when Proc |
744 | page_filter.call(page_number) |
745 | end
|
746 | end
|
#polygon(*points) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a polygon from the specified points.
#rectangle(point, width, height) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a rectangle given point
, width and
height`. The rectangle is
bounded by its upper-left corner.
#render(output = nil) ⇒ String
Renders the PDF document to string. Pass an open file descriptor to render to file.
Source Code
456 | def render(*arguments) |
457 | (1..page_count).each do |i| |
458 | go_to_page(i) |
459 | repeaters.each { |r| r.run(i) } |
460 | end
|
461 | |
462 | renderer.render(*arguments) |
463 | end
|
#render_file(filename) ⇒ void
This method returns an undefined value.
Renders the PDF document to file.
Source Code
472 | def render_file(filename) |
473 | File.open(filename, 'wb') { |f| render(f) } |
474 | end
|
#repeat(page_filter, options = {}, &block) ⇒ void
This method returns an undefined value.
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.
Also accepts an optional second argument for dynamic content which executes the code in the context of the filtered pages without using a Stamp.
Source Code
77 | def repeat(page_filter, options = {}, &block) |
78 | dynamic = options.fetch(:dynamic, false) |
79 | repeaters << Prawn::Repeater.new( |
80 | self, page_filter, dynamic, &block |
81 | )
|
82 | end
|
#rotate(angle, options = {}) { ... } ⇒ void Originally defined in module Graphics::Transformation
This method returns an undefined value.
Rotate the user space. If a block is not provided, then you must save and restore the graphics state yourself.
#rounded_polygon(radius, *points) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a rounded polygon from specified points using the radius to define bezier curves.
#rounded_rectangle(point, width, height, radius) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a rounded rectangle given point
, width
, height
, and radius
for the rounded corner. The rectangle is bounded by its upper-left corner.
#rounded_vertex(radius, *points) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Creates a rounded vertex for a line segment used for building a rounded polygon requires a radius to define bezier curve and three points. The first two points define the line segment and the third point helps define the curve for the vertex.
#save_font { ... } ⇒ void
This method returns an undefined value.
Saves the current font, and then yields. When the block finishes, the original font is restored.
Source Code
255 | def save_font |
256 | @font ||= find_font('Helvetica') |
257 | original_font = @font |
258 | original_size = @font_size |
259 | |
260 | yield
|
261 | ensure
|
262 | set_font(original_font, original_size) if original_font |
263 | end
|
#scale(factor, options = {}) { ... } ⇒ void Originally defined in module Graphics::Transformation
This method returns an undefined value.
Scale the user space. If a block is not provided, then you must save and restore the graphics state yourself.
#soft_mask { ... } ⇒ void Originally defined in module SoftMask
This method returns an undefined value.
Apply soft mask.
You must group soft mask and graphics it’s applied to under
save_graphics_state
because soft mask is a part of graphic state in PDF.
Note that soft mask is applied only to the following content in the
graphic state. Anything that comes before soft_mask
is drawn without
mask.
Conceptually, soft mask is an alpha channel. Luminosity of the drawing in the soft mask defines the transparency of the drawing the mask is applied to. 0.0 mask luminosity (“black”) results in a fully opaque target image and 1.0 mask luminosity (“white”) results in a fully transparent target image. Grey values result in some semi-transparent target image.
Note: you can use color in mask drawings but it makes harder to reason about the resulting value of alpha channel as it requires an additional luminosity calculation. However, this also allows achieving some advanced artistic effects (e.g. full-color photos in masks to get an effect similar to double exposure).
#span(width, options = {}) { ... } ⇒ void
This method returns an undefined value.
A span is a special purpose bounding box that allows a column of elements to be positioned relative to the margin_box.
This method is typically used for flowing a column of text from one page to the next.
Source Code
31 | def span(width, options = {}) |
32 | Prawn.verify_options([:position], options) |
33 | original_position = y |
34 | |
35 | # FIXME: Any way to move this upstream?
|
36 | left_boundary = |
37 | case options.fetch(:position, :left) |
38 | when :left |
39 | margin_box.absolute_left |
40 | when :center |
41 | margin_box.absolute_left + (margin_box.width / 2.0) - (width / 2.0) |
42 | when :right |
43 | margin_box.absolute_right - width |
44 | when Numeric |
45 | margin_box.absolute_left + options[:position] |
46 | else
|
47 | raise ArgumentError, 'Invalid option for :position' |
48 | end
|
49 | |
50 | # we need to bust out of whatever nested bounding boxes we're in.
|
51 | canvas do |
52 | bounding_box( |
53 | [
|
54 | left_boundary, |
55 | margin_box.absolute_top, |
56 | ],
|
57 | width: width, |
58 | ) do |
59 | self.y = original_position |
60 | yield
|
61 | end
|
62 | end
|
63 | end
|
#stamp(name) ⇒ void Originally defined in module Stamp
This method returns an undefined value.
Renders the stamp.
#stamp_at(name, point) ⇒ void Originally defined in module Stamp
This method returns an undefined value.
Renders the stamp at a position offset from the initial coords at which the elements of the stamp was created.
#start_new_page(options = {}) ⇒ void
This method returns an undefined value.
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.
Source Code
299 | def start_new_page(options = {}) |
300 | last_page = state.page |
301 | if last_page |
302 | last_page_size = last_page.size |
303 | last_page_layout = last_page.layout |
304 | last_page_margins = last_page.margins.dup |
305 | end
|
306 | |
307 | page_options = { |
308 | size: options[:size] || last_page_size, |
309 | layout: options[:layout] || last_page_layout, |
310 | margins: last_page_margins, |
311 | }
|
312 | if last_page |
313 | if last_page.graphic_state |
314 | new_graphic_state = last_page.graphic_state.dup |
315 | end
|
316 | |
317 | # erase the color space so that it gets reset on new page for fussy
|
318 | # pdf-readers
|
319 | new_graphic_state&.color_space = {} |
320 | |
321 | page_options[:graphic_state] = new_graphic_state |
322 | end
|
323 | |
324 | state.page = PDF::Core::Page.new(self, page_options) |
325 | |
326 | apply_margin_options(options) |
327 | generate_margin_box
|
328 | |
329 | # Reset the bounding box if the new page has different size or layout
|
330 | if last_page && (last_page.size != state.page.size || |
331 | last_page.layout != state.page.layout) |
332 | @bounding_box = @margin_box |
333 | end
|
334 | |
335 | use_graphic_settings
|
336 | |
337 | unless options[:orphan] |
338 | state.insert_page(state.page, @page_number) |
339 | @page_number += 1 |
340 | |
341 | if @background |
342 | canvas do |
343 | image(@background, scale: @background_scale, at: bounds.top_left) |
344 | end
|
345 | end
|
346 | @y = @bounding_box.absolute_top |
347 | |
348 | float do |
349 | state.on_page_create_action(self) |
350 | end
|
351 | end
|
352 | end
|
#stroke { ... } ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Strokes the current path. If a block is provided, yields to the block before closing the path. See Color for color details.
#stroke_axis(options = {}) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and strokes X and Y axes rulers beginning at the current bounding box origin (or at a custom location).
#stroke_bounds ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and strokes a rectangle represented by the current bounding box.
#stroke_color ⇒ String, Array<Number> #stroke_color(color) ⇒ void Also known as: stroke_color= Originally defined in module Graphics::Color
Sets or returns the line stroking color.
#stroke_curve(origin, dest, options = {}) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Strokes a Bezier curve between two points, bounded by two additional points.
#stroke_ellipse(point, radius1, radius2 = radius1) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and strokes an ellipse of x radius r1
and y radius r2
with the
centre-point at point
.
#fill_gradient(from, to, color1, color2, apply_margin_options: false) ⇒ void #fill_gradient(from, r1, to, r2, color1, color2, apply_margin_options: false) ⇒ void #fill_gradient(from: , to: , r1: nil, r2: nil, stops: , apply_margin_options: true) ⇒ void Originally defined in module Graphics::Patterns
Sets the stroke gradient.
#stroke_horizontal_line(x1, x2, options = {}) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Strokes a horizontal line from x1
to x2
at the current y position,
or the position specified by the :at option.
#stroke_horizontal_rule ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Strokes a horizontal line from the left border to the right border of the bounding box at the current y position.
#line(point1, point2) ⇒ void #line(x1, y1, x2, y2) ⇒ void Originally defined in module Graphics
Strokes a line from one point to another. Points may be specified as tuples or flattened argument list.
#stroke_polygon(*points) ⇒ Object Originally defined in module Graphics
Draws and strokes a polygon from the specified points.
@param points [Array<Array(Number, Number)>] @return [void]
#stroke_rectangle(point, width, height) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and strokes a rectangle given point
, width
, and height
. The
rectangle is bounded by its upper-left corner.
#stroke_rounded_polygon(radius, *points) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and strokes a rounded polygon from specified points, using
radius
to define Bezier curves.
#stroke_rounded_rectangle(point, width, height, radius) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws and strokes a rounded rectangle given point
, width
and
height
, and radius
for the rounded corner. The rectangle is bounded
by its upper-left corner.
#stroke_vertical_line(y1, y2, params) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Strokes a vertical line at the x coordinate given by :at
from y1
to
y2
.
#text(string, options = {}) ⇒ void Originally defined in module Text
This method returns an undefined value.
Draws text on the page.
If you want text to flow onto a new page or between columns, this is the method to use. If, instead, you want to place bounded text outside of the flow of a document (for captions, labels, charts, etc.), use Box or its convenience method #text_box.
Prawn attempts to wrap the text to fit within your current bounding box
(or margin_box
if no bounding box is being used). Text will flow onto
the next page when it reaches the bottom of the bounding box. Text wrap in
Prawn does not re-flow line breaks, so if you want fully automated text
wrapping, be sure to remove newlines before attempting to draw your
string.
Examples
pdf.text "Will be wrapped when it hits the edge of your bounding box"
pdf.text "This will be centered", align: :center
pdf.text "This will be right aligned", align: :right
pdf.text "This <i>includes <b>inline</b></i> <font size='24'>formatting</font>", inline_format: true
If your font contains kerning pair data that Prawn can parse, the text
will be kerned by default. You can disable kerning by including a false
:kerning
option. If you want to disable kerning on an entire document,
set default_kerning = false
for that document.
Text Positioning Details
The text is positioned at font.ascender
below the baseline, making it
easy to use this method within bounding boxes and spans.
Encoding
Note that strings passed to this function should be encoded as UTF-8. If you get unexpected characters appearing in your rendered document, check this.
If the current font is a built-in one, although the string must be encoded as UTF-8, only characters that are available in WinAnsi are allowed.
If an empty box is rendered to your PDF instead of the character you wanted it usually means the current font doesn’t include that character.
#text_box(string, options = {}) ⇒ String Originally defined in module Text
Draws the requested text into a box.
When the text overflows the rectangle, you shrink to fit, or truncate the text. Text boxes are independent of the document y position.
Encoding
Note that strings passed to this function should be encoded as UTF-8. If you get unexpected characters appearing in your rendered document, check this.
If the current font is a built-in one, although the string must be encoded as UTF-8, only characters that are available in WinAnsi are allowed.
If an empty box is rendered to your PDF instead of the character you wanted it usually means the current font doesn’t include that character.
#transformation_matrix(*matrix) { ... } ⇒ void Originally defined in module Graphics::Transformation
This method returns an undefined value.
Transform the user space (see notes for rotate regarding graphics state) Generally, one would use the #rotate, #scale, and #translate convenience methods instead of calling transformation_matrix directly
#translate(x, y) { ... } ⇒ void Originally defined in module Graphics::Transformation
This method returns an undefined value.
Translate the user space. If a block is not provided, then you must save and restore the graphics state yourself.
#transparent(opacity, stroke_opacity = opacity) { ... } ⇒ void Originally defined in module Graphics::Transparency
This method returns an undefined value.
Set opacity.
#undash ⇒ void Originally defined in module Graphics::Dash
This method returns an undefined value.
Stops dashing, restoring solid stroked lines and curves.
#vertical_line(y1, y2, params) ⇒ void Originally defined in module Graphics
This method returns an undefined value.
Draws a vertical line at the x coordinate given by :at
from y1
to
y2
.
#width_of(string, options = {}) ⇒ Number
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/OTF, 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.
Source Code
150 | def width_of(string, options = {}) |
151 | if options.key?(:inline_format) |
152 | p = options[:inline_format] |
153 | p = [] unless p.is_a?(Array) |
154 | |
155 | # Build up an Arranger with the entire string on one line, finalize it,
|
156 | # and find its width.
|
157 | arranger = Prawn::Text::Formatted::Arranger.new(self, options) |
158 | arranger.consumed = text_formatter.format(string, *p) |
159 | arranger.finalize_line |
160 | |
161 | arranger.line_width |
162 | else
|
163 | width_of_string(string, options) |
164 | end
|
165 | end
|