Class: Prawn::Document

Inherits:
Object
  • Object
show all
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

Extension Attributes collapse

Stable API collapse

Experimental API collapse

Extension API collapse

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.

Examples:

New document, US Letter paper, portrait orientation

pdf = Prawn::Document.new

New document, A4 paper, landscaped

pdf = Prawn::Document.new(page_size: "A4", page_layout: :landscape)

New document, Custom size

pdf = Prawn::Document.new(page_size: [200, 300])

New document, with background

pdf = Prawn::Document.new(
  background: "#{Prawn::DATADIR}/images/pigs.jpg"
)

Parameters:

  • options (Hash{Symbol => any}) (defaults to: {})

Options Hash (options):

  • :page_size (String, Array(Number, Number)) — default: LETTER

    One of the PDF::Core::PageGeometry sizes.

  • :page_layout (:portrait, :landscape)

    Page orientation.

  • :margin (Number, Array<Number>) — default: [32]

    Sets the margin on all sides in points.

  • :left_margin (Number) — default: 32

    Sets the left margin in points.

  • :right_margin (Number) — default: 32

    Sets the right margin in points.

  • :top_margin (Number) — default: 32

    Sets the top margin in points.

  • :bottom_margin (Number) — default: 32

    Sets the bottom margin in points.

  • :skip_page_creation (Boolean) — default: false

    Creates a document without starting the first page.

  • :compress (Boolean) — default: false

    Compresses content streams before rendering them.

  • :background (String?) — default: nil

    An image path to be used as background on all pages.

  • :background_scale (Number?) — default: 1

    Background image scale.

  • :info (Hash{Symbol => any}?) — default: nil

    Generic hash allowing for custom metadata properties.

  • :text_formatter (Object) — default: Prawn::Text::Formatted::Parser

    The text formatter to use for :inline_formatted text.

Source Code
lib/prawn/document.rb, line 227
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_boxPrawn::Document::BoundingBox

Current margin box.

Source Code
lib/prawn/document.rb, line 109
109
def margin_box
110
  @margin_box
111
end

#margins{:left, :top, :right, :bottom => Number} (readonly)

Current page margins.

Returns:

  • ({:left, :top, :right, :bottom => Number})
Source Code
lib/prawn/document.rb, line 113
113
def margins
114
  @margins
115
end

#page_numberInteger

Current page number.

Returns:

  • (Integer)
Source Code
lib/prawn/document.rb, line 121
121
def page_number
122
  @page_number
123
end

#text_formatterObject

Current text formatter. By default it’s Text::Formatted::Parser

Returns:

  • (Object)
Source Code
lib/prawn/document.rb, line 127
127
def text_formatter
128
  @text_formatter
129
end

#yNumber

Absolute cursor position.

Returns:

  • (Number)
Source Code
lib/prawn/document.rb, line 117
117
def y
118
  @y
119
end

Class Method Details

.extensionsArray<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.

Examples:

module MyFancyModule
  def party!
    text "It's a big party!"
  end
end

Prawn::Document.extensions << MyFancyModule

Prawn::Document.generate("foo.pdf") do
  party!
end

Returns:

  • (Array<Module>)
Source Code
lib/prawn/document.rb, line 95
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
lib/prawn/document.rb, line 161
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.

Examples:

pdf.fill_color('0000ff')
pdf.fill_rectangle([x, y + 25], 50, 50)
pdf.blend_mode(:Multiply) do
  pdf.fill_color('ff0000')
  pdf.fill_circle([x, y], 25)
end

Parameters:

  • blend_mode (Symbol, Array<Symbol>) (defaults to: :Normal)

Yields:

#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.

This method returns an undefined value.

Parameters:

  • point (Array(Number, Number))

    top left corner of the new bounding box

  • options (Hash{Symbol => any}) (defaults to: {})

Options Hash (options):

  • :width (Number)

    width of the new bounding box, must be specified.

  • :height (Number)

    height of the new bounding box, stretchy box if omitted.

Yield Parameters:

Yield Returns:

  • (void)
Source Code
lib/prawn/document/bounding_box.rb, line 174
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

#boundsPrawn::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.

Examples:

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

Returns:

Source Code
lib/prawn/document.rb, line 504
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.

Parameters:

Returns:

Source Code
lib/prawn/document.rb, line 523
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.

Examples:

pdf.canvas do
  pdf.line pdf.bounds.bottom_left, pdf.bounds.top_right
end

Yield Returns:

  • (void)
Source Code
lib/prawn/document/bounding_box.rb, line 191
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_styleSymbol Also known as: cap_style= Originally defined in module Graphics::CapStyle

Sets the cap style for stroked lines and curves.

Overloads:

  • #cap_style(style) ⇒ void

    This method returns an undefined value.

    Parameters:

    • style (:butt, :round, :projecting_square)

      (:butt)

  • #cap_styleSymbol

    Returns:

    • (Symbol)

#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.

Examples:

pdf.circle [100, 100], 25

Parameters:

  • center (Array(Number, Number))
  • radius (Number)

#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.

Yields:

#close_pathObject 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.

This method returns an undefined value.

Parameters:

  • point (Array(Number, Number))
  • options (Hash{Symbol => any}) (defaults to: {})

Options Hash (options):

  • :width (Number)

    width of the new column box, must be specified.

  • :height (Number)

    height of the new column box, stretchy box if omitted.

  • :hold_position (Boolean)

    whether to put cursor at the bottom of the column box.

  • :columns (Integer) — default: 3
  • :spacer (Number) — default: font_size
  • :reflow_margins (Boolean) — default: false

Yield Parameters:

Source Code
lib/prawn/document/column_box.rb, line 34
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.

Examples:

pdf.create_stamp("my_stamp") {
  pdf.fill_circle([10, 15], 5)
  pdf.draw_text("hello world", at: [20, 10])
}

Parameters:

  • name (String)

    Stamp name.

Yields:

  • Stamp content.

Raises:

#cursorNumber

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

Returns:

  • (Number)
Source Code
lib/prawn/document.rb, line 415
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

Examples:

pdf.curve [50, 100], [100, 100], bounds: [[90, 90], [75, 75]]

Parameters:

  • origin (Array(Number, Number))
  • dest (Array(Number, Number))
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :bounds (Array(Array(Number, Number), Array(Number, Number)))

#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.

Examples:

pdf.curve_to [100, 100], bounds: [[90, 90], [75, 75]]

Parameters:

  • dest (Array(Number, Number))
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :bounds (Array(Array(Number, Number), Array(Number, Number)))

#dashHash{: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.

Overloads:

  • #dashHash{:dash => Number, Array<Number>, :space => Number, nil, :phase => Number}

    Returns the current dash pattern.

    Returns:

    • (Hash{:dash => Number, Array<Number>, :space => Number, nil, :phase => Number})
  • #dash(length, options = {}) ⇒ void

    This method returns an undefined value.

    Sets the dash pattern for stroked lines and curves.

    Integers or Floats may be used for length and the option values. Dash units are in PDF points (1/72 inch).

    Parameters:

    • length (Number, Array<Number>)
      • If length is a Number (Integer or Float), it specifies the length of the dash and of the gap. The length of the gap can be customized by setting the :space option.

        Examples:

        length = 3
        3 on, 3 off, 3 on, 3 off, …
        length = 3, :space = 2
        3 on, 2 off, 3 on, 2 off, …
      • If length is an array, it specifies the lengths of alternating dashes and gaps. The numbers must be non-negative and not all zero. The :space option is ignored in this case.

        Examples:

        length = [2, 1]
        2 on, 1 off, 2 on, 1 off, …
        length = [3, 1, 2, 3]
        3 on, 1 off, 2 on, 3 off, 3 on, 1 off, …
        length = [3, 0, 1]
        3 on, 0 off, 1 on, 3 off, 0 on, 1 off, …
    • options (Hash{Symbol => any}) (defaults to: {})

    Options Hash (options):

    • :space (Number)

      The space between the dashes (only used when length is not an array).

    • :phase (Number) — default: 0

      The distance into the dash pattern at which to start the dash. For example, a phase of 0 starts at the beginning of the dash; whereas, if the phase is equal to the length of the dash, then stroking will begin at the beginning of the space.

#dashed?Boolean Originally defined in module Graphics::Dash

Returns true when stroke is dashed, false otherwise.

Returns:

  • (Boolean)

#define_grid(options = {}) ⇒ Grid

Note:

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

Parameters:

  • options (Hash{Symbol => any}) (defaults to: {})

Options Hash (options):

  • :columns (Integer)

    Number of columns in the grid.

  • :rows (Integer)

    Number of rows in the grid.

  • :gutter (Number)

    Gutter size. :row_gutter and :column_gutter are ignored if specified.

  • :row_gutter (Number)

    Row gutter size.

  • :column_gutter (Number)

    Column gutter size.

Returns:

Source Code
lib/prawn/grid.rb, line 24
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.

Examples:

pdf = Prawn::Document.new
pdf.page_count #=> 1
3.times { pdf.start_new_page }
pdf.page_count #=> 4
pdf.delete_page(-1)
pdf.page_count #=> 3

Parameters:

  • index (Integer)

Returns:

  • (Boolean)
Source Code
lib/prawn/document.rb, line 366
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.

Parameters:

  • text (String)
  • options (Hash{Symbol => any})

Options Hash (options):

  • :at (Array(Number, Number))

    Required. The position at which to start the text.

  • :kerning (Boolean) — default: value of default_kerning?

    Whether or not to use kerning (if it is available with the current font).

  • :size (Number) — default: current font size

    The font size to use.

  • :style (Symbol) — default: current style

    The style to use. The requested style must be part of the current font family.

  • :rotate (Number)

    The angle to which to rotate text.

Raises:

  • (ArgumentError)

    If :at option is omitted or `:align</tt> option is included.

#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.

Parameters:

  • text (String)
  • options (Hash{Symbol => any})

Options Hash (options):

  • :at (Array(Number, Number))

    The position at which to start the text.

  • :kerning (Boolean)

    Whether or not to use kerning (if it is available with the current font).

  • :size (Number)

    The font size to use.

  • :style (Symbol)

    The style to use. The requested style must be part of the current font family.

  • :rotate (Number)

    The angle to which to rotate text.

#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.

Examples:

Draws an ellipse with x-radius 25 and y-radius 50

pdf.ellipse [100, 100], 25, 50

Parameters:

  • point (Array(Number, Number))
  • radius1 (Number)
  • radius2 (Number) (defaults to: radius1)

#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.

Parameters:

  • options (Hash{Symbol => any}) (defaults to: {})

Options Hash (options):

  • :user_password (String)

    Password required to open the document. If this is omitted or empty, no password will be required. The document will still be encrypted, but anyone can read it.

  • :owner_password (String, :random)

    Password required to make modifications to the document or change or override its permissions. If this is set to :random, a random password will be used; this can be useful if you never want users to be able to override the document permissions.

  • :permissions (Hash{Symbol => Boolean})

    A hash mapping permission symbols (see below) to true or false. true means “permitted”, and false means “not permitted”. All permissions default to true.

    The following permissions can be specified:

    • :print_document – Print document.
    • :modify_contents – Modify contents of document (other than text annotations and interactive form fields).
    • :copy_contents – Copy text and graphics from document.
    • :modify_annotations – Add or modify text annotations and interactive form fields.

#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.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :fill_rule (Symbol)

Yields:

#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.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :fill_rule (Symbol)

Yields:

#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.

Parameters:

  • center (Array(Number, Number))
  • radius (Number)

#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.

Parameters:

  • point (Array(Number, Number))
  • radius1 (Number)
  • radius2 (Number) (defaults to: radius1)

#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.

Parameters:

  • points (Array<Array(Number, Number)>)

#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.

Parameters:

  • point (Array(Number, Number))
  • width (Number)
  • height (Number)

#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.

Parameters:

  • point (Array(Number, Number))
  • width (Number)
  • height (Number)
  • radius (Number)

#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.

Parameters:

  • center (Array(Number, Number))
  • radius (Number)

#fill_colorString, Array<Number> #fill_color(color) ⇒ void Also known as: fill_color= Originally defined in module Graphics::Color

Sets or returns the fill color.

Overloads:

  • #fill_colorString, Array<Number>

    Returns the current fill color.

    Returns:

    • (String, Array<Number>)
  • #fill_color(color) ⇒ void

    This method returns an undefined value.

    Sets the fill color.

    If a single argument is provided, it should be a 6 digit HTML color code.

    pdf.fill_color "f0ffc1"
    

    If 4 arguments are provided, the color is assumed to be a CMYK value. Values range is 0–100.

    pdf.fill_color 0, 99, 95, 0
    

    Parameters:

    • color (String, Array<Number>)

#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.

Parameters:

  • point (Array(Number, Number))
  • radius1 (Number)
  • radius2 (Number) (defaults to: radius1)

#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.

Overloads:

  • #fill_gradient(from, to, color1, color2, apply_margin_options: false) ⇒ void

    This method returns an undefined value.

    Set an axial (linear) fill gradient.

    Parameters:

    • from (Array(Number, Number))

      Starting point of the gradient.

    • to (Array(Number, Number))

      ending point of the gradient.

    • color1 (Color)

      starting color of the gradient.

    • color2 (Color)

      ending color of the gradient.

    • apply_transformations (Boolean)

      (false) If set true, will transform the gradient’s co-ordinate space so it matches the current co-ordinate space of the document. This option will be the default from Prawn v3, and is default true if you use the all-keyword version of this method. The default for the positional arguments version (this one), false, will mean if you (for example) scale your document by 2 and put a gradient inside, you will have to manually multiply your co-ordinates by 2 so the gradient is correctly positioned.

  • #fill_gradient(from, r1, to, r2, color1, color2, apply_margin_options: false) ⇒ void

    This method returns an undefined value.

    Set a radial fill gradient.

    Parameters:

    • from (Array(Number, Number))

      Starting point of the gradient.

    • r1 (Number)

      Radius of the starting circle of a radial gradient. The circle is centered at from.

    • to (Array(Number, Number))

      Ending point of the gradient.

    • r2 (Number)

      Radius of the ending circle of a radial gradient. The circle is centered at to.

    • color1 (Color)

      Starting color.

    • color2 (Color)

      Ending color.

    • apply_transformations (Boolean)

      (false) If set true, will transform the gradient’s co-ordinate space so it matches the current co-ordinate space of the document. This option will be the default from Prawn v3, and is default true if you use the all-keyword version of this method. The default for the positional arguments version (this one), false, will mean if you (for example) scale your document by 2 and put a gradient inside, you will have to manually multiply your co-ordinates by 2 so the gradient is correctly positioned.

  • #fill_gradient(from: , to: , r1: nil, r2: nil, stops: , apply_margin_options: true) ⇒ void

    This method returns an undefined value.

    Set the fill gradient.

    Examples:

    Draw a horizontal axial gradient that starts at red on the left and ends at blue on the right

    fill_gradient from: [0, 0], to: [100, 0], stops: ['ff0000', '0000ff']

    Draw a horizontal radial gradient that starts at red, is green 80% through, and finishes blue

    fill_gradient from: [0, 0], r1: 0, to: [100, 0], r2: 180,
      stops: { 0 => 'ff0000', 0.8 => '00ff00', 1 => '0000ff' }

    Parameters:

    • from (Array(Number, Number)) (defaults to: )

      Starting point of the gradient.

    • r1 (Number, nil) (defaults to: nil)

      Radius of the starting circle of a radial gradient. The circle is centered at from. If omitted a linear gradient will be produced.

    • to (Array(Number, Number)) (defaults to: )

      Ending point of the gradient.

    • r2 (Number, nil) (defaults to: nil)

      Radius of the ending circle of a radial gradient. The circle is centered at to.

    • stops (Array<Color>, Hash{Number => Color}) (defaults to: )

      Color stops. Each stop is either just a color, in which case the stops will be evenly distributed across the gradient, or a hash where the key is a position between 0 and 1 indicating what distance through the gradient the color should change, and the value is a color.

    • apply_transformations (Boolean)

      (true) If set true, will transform the gradient’s co-ordinate space so it matches the current co-ordinate space of the document. This option will be the default from Prawn v3, and is default true if you use the all-keyword version of this method (this one). The default for the old arguments format, false, will mean if you (for example) scale your document by 2 and put a gradient inside, you will have to manually multiply your co-ordinates by 2 so the gradient is correctly positioned.

#fill_polygon(*points) ⇒ void Originally defined in module Graphics

This method returns an undefined value.

Draws and fills a polygon from the specified points.

Parameters:

  • points (Array<Array(Number, Number)>)

#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.

Parameters:

  • point (Array(Number, Number))
  • width (Number)
  • height (Number)

#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.

Parameters:

  • radius (Number)
  • points (Array<Array(Number, Number)>)

#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.

Parameters:

  • point (Array(Number, Number))
  • width (Number)
  • height (Number)
  • radius (Number)

#floatvoid

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.

Examples:

pdf.text "A"

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

pdf.text "B"
Source Code
lib/prawn/document.rb, line 442
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.

Parameters:

  • name (String) (defaults to: nil)

    font name. It can be:

    • One of 14 PDF built-in fonts.
    • A font file path.
    • A font name defined in #font_families
  • options (Hash{Symbol => any}) (defaults to: DEFAULT_OPTS)

Options Hash (options):

  • :style (Symbol)

    font style

Yields:

Returns:

See Also:

Source Code
lib/prawn/font.rb, line 56
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_familiesHash{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.

Returns:

  • (Hash{String => Hash{Symbol => String, Hash{Symbol => String}}})
Source Code
lib/prawn/font.rb, line 212
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_sizeNumber #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.

Examples:

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

Overloads:

  • #font_sizeNumber

    Returns vurrent font size.

    Returns:

    • (Number)

      vurrent font size

  • #font_size(points) { ... } ⇒ void

    This method returns an undefined value.

    Parameters:

    • points (Number)

      new font size

    Yields:

    • if block is provided font size is set only for the duration of the block

Source Code
lib/prawn/font.rb, line 106
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.

Parameters:

  • size (Number)

Returns:

  • (Number)
Source Code
lib/prawn/font.rb, line 119
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.

Examples:

text([{ :text => "hello" },
      { :text => "world",
        :size => 24,
        :styles => [:bold, :italic] }])

Parameters:

  • array (Array<Hash>)

    array of text fragments. See Prawn::Text::Formatted#formatted_text_box for more information on the structure of this array.

  • options (Hash{Symbol => any}) (defaults to: {})
  • option (Hash)

    a customizable set of options

Options Hash (options):

  • :inline_format (Boolean)

    If true, then the string parameter is interpreted as a HTML-esque string that recognizes the following tags (assuming the default text formatter is used):

    • <b></b> — bold style.
    • <i></i> — italic style.
    • <u></u> — underline.
    • <strikethrough></strikethrough> — strikethrough.
    • <sub></sub> — subscript.
    • <sup></sup> — superscript.
    • <font></font> — with the following attributes (using double or single quotes):
      • name="Helvetica" — the font. The font name must be an AFM font with the desired faces or must be a font that is already registered using Document#font_families.
      • size="24" — attribute for setting size.
      • character_spacing="2.5" — character spacing.
    • <color></color> — text color
      • rgb="ffffff" or rgb="#ffffff" — RGB color
      • c="100" m="100" y="100" k="100" — CMYK color
    • <link></link> - link, with the following attributes:
      • href="http://example.com" — an external link. Note that you must explicitly underline and color using the appropriate tags if you which to draw attention to the link.
  • :kerning (Boolean) — default: value of document.default_kerning?

    Whether or not to use kerning (if it is available with the current font).

  • :size (Number) — default: current ofnt size

    The font size to use.

  • :color (Color)
  • :character_spacing (Number) — default: 0

    The amount of space to add to or remove from the default character spacing.

  • :style (Symbol) — default: current style

    The style to use. The requested style must be part of the current font family.

  • :indent_paragraphs (Number)

    The amount to indent the first line of each paragraph. Omit this option if you do not want indenting.

  • :direction (:ltr, :rtl) — default: value of document.text_direction

    Direction of the text.

  • :fallback_fonts (Array<String>)

    An array of font names. Each name must be the name of an AFM font or the name that was used to register a family of TTF fonts (see Document#font_families). If present, then each glyph will be rendered using the first font that includes the glyph, starting with the current font and then moving through :fallback_fonts.

  • :valign (:top, :center, :bottom) — default: :top

    Vertical alignment within the bounding box.

  • :leading (Object) — default: Number

    (value of document.default_leading) Additional space between lines.

  • :final_gap (Boolean) — default: true

    If true, then the space between each line is included below the last line; otherwise, Document#y is placed just below the descender of the last line printed.

  • :mode (Symbol) — default: :fill

    The text rendering mode to use. Use this to specify if the text should render with the fill color, stroke color or both.

    • :fill - fill text (default)
    • :stroke - stroke text
    • :fill_stroke - fill, then stroke text
    • :invisible - invisible text
    • :fill_clip - fill text then add to path for clipping
    • :stroke_clip - stroke text then add to path for clipping
    • :fill_stroke_clip - fill then stroke text, then add to path for clipping
    • :clip - add text to path for clipping

Raises:

  • (ArgumentError)

    if :at option included

  • (Prawn::Errrors::CannotFit)

    if not wide enough to print any text

See Also:

  • for a list of valid text rendering modes.

#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.

Examples:

formatted_text_box([{ :text => "hello" },
                    { :text => "world",
                      :size => 24,
                      :styles => [:bold, :italic] }])

Parameters:

  • array (Array<Hash{Symbol => any}>)

    Formatted text is an array of hashes, where each hash defines text and format information. The following hash options are supported:

    • :text — the text to format according to the other hash options.
    • :styles — an array of styles to apply to this text. Available styles include :bold, :italic, :underline, :strikethrough, :subscript, and :superscript.
    • :size —a number denoting the font size to apply to this text.
    • :character_spacing — a number denoting how much to increase or decrease the default spacing between characters.
    • :font — the name of a font. The name must be an AFM font with the desired faces or must be a font that is already registered using Document#font_families.
    • :color — anything compatible with Graphics::Color#fill_color and Graphics::Color#stroke_color.
    • :link` — a URL to which to create a link. A clickable link will be created to that URL. Note that you must explicitly underline and color using the appropriate tags if you which to draw attention to the link.
    • :anchor — a destination that has already been or will be registered using PDF::Core::Destinations#add_dest. A clickable link will be created to that destination. Note that you must explicitly underline and color using the appropriate tags if you which to draw attention to the link.
    • :local — a file or application to be opened locally. A clickable link will be created to the provided local file or application. If the file is another PDF, it will be opened in a new window. Note that you must explicitly underline and color using the appropriate options if you which to draw attention to the link.
    • :draw_text_callback — if provided, this Proc will be called instead of Prawn::Text#draw_text! once per fragment for every low-level addition of text to the page.
    • :callback — an object (or array of such objects) with two methods: #render_behind and #render_in_front, which are called immediately prior to and immediately after rendering the text fragment and which are passed the fragment as an argument.
  • options (Hash{Symbol => any}) (defaults to: {})

    Accepts the same options as Box.

Returns:

  • (Array<Hash>)

    A formatted text array representing any text that did not print under the current settings.

Raises:

  • (Prawn::Text::Formatted::Arranger::BadFontFamily)

    If no font family is defined for the current font.

  • (Prawn::Errors::CannotFit)

    If not wide enough to print any text.

#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.

Parameters:

  • page_number (Integer)
Source Code
lib/prawn/document.rb, line 395
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

#gridGrid #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.

Overloads:

  • #gridGrid

    Get current grid.

    Returns:

  • #grid(row, column) ⇒ GridBox

    Get a grid box.

    Parameters:

    • row (Integer)
    • column (Integer)

    Returns:

  • #grid(box1, box2) ⇒ MultiBox

    Get a grid multi-box.

    Parameters:

    • box1 (Array(Integer, Integer))

      Start box coordinates.

    • box2 (Array(Integer, Integer))

      End box coordinates.

    Returns:

Source Code
lib/prawn/grid.rb, line 50
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

Note:

This method takes the same options as #text, except :indent_paragraphs.

This method returns an undefined value.

Gets height of text in PDF points.

Examples:

text_height = height_of("hello\nworld")

Parameters:

  • string (String)
  • options (Hash{Symbol => any}) (defaults to: {})
  • option (Hash)

    a customizable set of options

Options Hash (options):

  • :inline_format (Boolean)

    If true, then the string parameter is interpreted as a HTML-esque string that recognizes the following tags (assuming the default text formatter is used):

    • <b></b> — bold style.
    • <i></i> — italic style.
    • <u></u> — underline.
    • <strikethrough></strikethrough> — strikethrough.
    • <sub></sub> — subscript.
    • <sup></sup> — superscript.
    • <font></font> — with the following attributes (using double or single quotes):
      • name="Helvetica" — the font. The font name must be an AFM font with the desired faces or must be a font that is already registered using Document#font_families.
      • size="24" — attribute for setting size.
      • character_spacing="2.5" — character spacing.
    • <color></color> — text color
      • rgb="ffffff" or rgb="#ffffff" — RGB color
      • c="100" m="100" y="100" k="100" — CMYK color
    • <link></link> - link, with the following attributes:
      • href="http://example.com" — an external link. Note that you must explicitly underline and color using the appropriate tags if you which to draw attention to the link.
  • :kerning (Boolean) — default: value of document.default_kerning?

    Whether or not to use kerning (if it is available with the current font).

  • :size (Number) — default: current ofnt size

    The font size to use.

  • :color (Color)
  • :character_spacing (Number) — default: 0

    The amount of space to add to or remove from the default character spacing.

  • :style (Symbol) — default: current style

    The style to use. The requested style must be part of the current font family.

  • :direction (:ltr, :rtl) — default: value of document.text_direction

    Direction of the text.

  • :fallback_fonts (Array<String>)

    An array of font names. Each name must be the name of an AFM font or the name that was used to register a family of TTF fonts (see Document#font_families). If present, then each glyph will be rendered using the first font that includes the glyph, starting with the current font and then moving through :fallback_fonts.

  • :valign (:top, :center, :bottom) — default: :top

    Vertical alignment within the bounding box.

  • :leading (Object) — default: Number

    (value of document.default_leading) Additional space between lines.

  • :final_gap (Boolean) — default: true

    If true, then the space between each line is included below the last line; otherwise, Document#y is placed just below the descender of the last line printed.

  • :mode (Symbol) — default: :fill

    The text rendering mode to use. Use this to specify if the text should render with the fill color, stroke color or both.

    • :fill - fill text (default)
    • :stroke - stroke text
    • :fill_stroke - fill, then stroke text
    • :invisible - invisible text
    • :fill_clip - fill text then add to path for clipping
    • :stroke_clip - stroke text then add to path for clipping
    • :fill_stroke_clip - fill then stroke text, then add to path for clipping
    • :clip - add text to path for clipping

Raises:

  • (ArgumentError)

    if :at option included

  • (Prawn::Errrors::CannotFit)

    if not wide enough to print any text

  • (NotImplementedError)

    if :indent_paragraphs option included.

See Also:

#height_of_formatted(array, options = {}) ⇒ void Originally defined in module Text

Note:

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.

Examples:

height_of_formatted([{ :text => "hello" },
                     { :text => "world",
                       :size => 24,
                       :styles => [:bold, :italic] }])

Parameters:

  • array (Array<Hash>)

    text fragments.

  • options (Hash{Symbol => any}) (defaults to: {})
  • option (Hash)

    a customizable set of options

Options Hash (options):

  • :inline_format (Boolean)

    If true, then the string parameter is interpreted as a HTML-esque string that recognizes the following tags (assuming the default text formatter is used):

    • <b></b> — bold style.
    • <i></i> — italic style.
    • <u></u> — underline.
    • <strikethrough></strikethrough> — strikethrough.
    • <sub></sub> — subscript.
    • <sup></sup> — superscript.
    • <font></font> — with the following attributes (using double or single quotes):
      • name="Helvetica" — the font. The font name must be an AFM font with the desired faces or must be a font that is already registered using Document#font_families.
      • size="24" — attribute for setting size.
      • character_spacing="2.5" — character spacing.
    • <color></color> — text color
      • rgb="ffffff" or rgb="#ffffff" — RGB color
      • c="100" m="100" y="100" k="100" — CMYK color
    • <link></link> - link, with the following attributes:
      • href="http://example.com" — an external link. Note that you must explicitly underline and color using the appropriate tags if you which to draw attention to the link.
  • :kerning (Boolean) — default: value of document.default_kerning?

    Whether or not to use kerning (if it is available with the current font).

  • :size (Number) — default: current ofnt size

    The font size to use.

  • :color (Color)
  • :character_spacing (Number) — default: 0

    The amount of space to add to or remove from the default character spacing.

  • :style (Symbol) — default: current style

    The style to use. The requested style must be part of the current font family.

  • :direction (:ltr, :rtl) — default: value of document.text_direction

    Direction of the text.

  • :fallback_fonts (Array<String>)

    An array of font names. Each name must be the name of an AFM font or the name that was used to register a family of TTF fonts (see Document#font_families). If present, then each glyph will be rendered using the first font that includes the glyph, starting with the current font and then moving through :fallback_fonts.

  • :valign (:top, :center, :bottom) — default: :top

    Vertical alignment within the bounding box.

  • :leading (Object) — default: Number

    (value of document.default_leading) Additional space between lines.

  • :final_gap (Boolean) — default: true

    If true, then the space between each line is included below the last line; otherwise, Document#y is placed just below the descender of the last line printed.

  • :mode (Symbol) — default: :fill

    The text rendering mode to use. Use this to specify if the text should render with the fill color, stroke color or both.

    • :fill - fill text (default)
    • :stroke - stroke text
    • :fill_stroke - fill, then stroke text
    • :invisible - invisible text
    • :fill_clip - fill text then add to path for clipping
    • :stroke_clip - stroke text then add to path for clipping
    • :fill_stroke_clip - fill then stroke text, then add to path for clipping
    • :clip - add text to path for clipping

Raises:

  • (ArgumentError)

    if :at option included

  • (Prawn::Errrors::CannotFit)

    if not wide enough to print any text

  • (NotImplementedError)

    if :indent_paragraphs option included.

See Also:

  • for a list of valid text rendering modes.
  • #height_of

#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.

Examples:

Draw a line from [25, 75] to [100, 75]

horizontal_line 25, 100, at: 75

Parameters:

  • x1 (Number)
  • x2 (Number)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :at (Number)

#horizontal_rulevoid 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.

Examples:

Prawn::Document.generate("image2.pdf", page_layout: :landscape) do
  pigs = "#{Prawn::DATADIR}/images/pigs.jpg"
  image pigs, at: [50,450], width: 450

  dice = "#{Prawn::DATADIR}/images/dice.png"
  image dice, at: [50, 450], scale: 0.75
end

Parameters:

  • file (String, IO)

    Path to file or an object that responds to #read and #rewind.

  • options (Hash{Symbol => any}) (defaults to: {})

Options Hash (options):

  • :at (Array(Number, Number))

    The location of the top left corner of the image. If provided, the image will be place in the current page but the text position will not be changed.

  • :position (:left, :center, :right, Number)

    Horizontal position relative to the current bounding box.

  • :vposition (:topm :center, :bottom, Number)

    Vertical position relative to the current bounding box.

  • :height (Number) — default: actual height of the image

    The height of the image.

  • :width (Number) — default: actual width of the image

    The width of the image.

  • :scale (Number)

    Scale the dimensions of the image proportionally.

  • :fit (Array(Number, Number))

    Scale the dimensions of the image proportionally to fit inside the rectangle of specified size (width, height).

Returns:

  • (Prawn::Images::Image)

    An image handler. All image handlers provided by Prawn are subclasses of Image. This object can be used to check the image dimensions and get other format-specific information.

See Also:

#indent(left, right = 0) { ... } ⇒ void

This method returns an undefined value.

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

Examples:

pdf.text "some text"
pdf.indent(20) do
  pdf.text "This is indented 20 points"
end
pdf.text "This starts 20 points left of the above line " +
         "and is flush with the first line"
pdf.indent 20, 20 do
  pdf.text "This line is indented on both sides."
end

Parameters:

  • left (Number)
  • right (Number) (defaults to: 0)

Yields:

Source Code
lib/prawn/document.rb, line 615
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.

Parameters:

  • options (Hash)
Source Code
lib/prawn/document.rb, line 767
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.

Overloads:

  • #join_style:miter, ...

    Get current join style.

    Returns:

    • (:miter, :round, :bevel)
  • #join_style(style) ⇒ void
    Note:

    If this method is never called, :miter will be used for join style throughout the document.

    This method returns an undefined value.

    Set join style.

    Parameters:

    • style (:miter, :round, :bevel)

#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.

Examples:

pdf.line [100, 100], [200, 250]
pdf.line(100, 100, 200, 250)

Overloads:

  • #line(point1, point2) ⇒ void

    This method returns an undefined value.

    Parameters:

    • point1 (Array(Number, Number))
    • point2 (Array(Number, Number))
  • #line(x1, y1, x2, y2) ⇒ void

    This method returns an undefined value.

    Parameters:

    • x1 (Number)
    • y1 (Number)
    • x2 (Number)
    • y2 (Number)

#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:

Examples:

pdf.line_to [50, 50]
pdf.line_to(50, 50)

Overloads:

  • #line_to(point) ⇒ void

    This method returns an undefined value.

    Parameters:

    • point (Array(Number, Number))
  • #line_to(x, y) ⇒ void

    This method returns an undefined value.

    Parameters:

    • x (Number)
    • y (Number)

#line_widthNumber #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).

Examples:

pdf.line_width #=> 1
pdf.line_width(5)
pdf.line_width #=> 5

Overloads:

  • #line_widthNumber

    Returns:

    • (Number)
  • #line_width(width) ⇒ void

    This method returns an undefined value.

    Parameters:

    • width (Number)

#line_width=(width) ⇒ void Originally defined in module Graphics

This method returns an undefined value.

Sets line thickness to the width specified.

Parameters:

  • width (Number)

#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.

Parameters:

  • new_y (Number)
Source Code
lib/prawn/document.rb, line 423
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.

Parameters:

  • amount (Number)
Source Code
lib/prawn/document.rb, line 541
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.

Examples:

pdf.move_to [100, 50]
pdf.move_to(100, 50)

Overloads:

  • #move_to(point) ⇒ void

    This method returns an undefined value.

    Parameters:

    • point (Array(Number, Number))
  • #move_to(x, y) ⇒ void

    This method returns an undefined value.

    Parameters:

    • x (Number)
    • y (Number)

#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.

Parameters:

  • amount (Number)
Source Code
lib/prawn/document.rb, line 532
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.

Examples:

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

Prawn::Document.generate("page_with_numbering.pdf") do
  number_pages "<page> in a total of <total>", {
    start_count_at: 5,
    page_filter: lambda { |pg| pg != 1 },
    at: [bounds.right - 50, 0],
    align: :right,
    size: 14
  }
end

Parameters:

  • string (String)

    Template string for page number wording. Should include <page> and, optionally, <total>.

  • options (Hash{Symbol => any}) (defaults to: {})

    A hash for page numbering and text box options.

Options Hash (options):

  • :page_filter (Object)

    [] A filter to specify which pages to place page numbers on. Refer to the method #page_match?

  • :start_count_at (Integer)

    The starting count to increment pages from.

  • :total_pages (Integer)

    If provided, will replace <total> with the value given. Useful to override the total number of pages when using the start_count_at option.

  • :color (String, Array<Number>)

    Text fill color.

Source Code
lib/prawn/document.rb, line 652
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

#outlinePrawn::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.

Returns:

Source Code
lib/prawn/outline.rb, line 12
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.

Examples:

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"

Parameters:

  • y (Number)

Yields:

Source Code
lib/prawn/document.rb, line 592
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

Examples:

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"

Parameters:

  • y (Number)

Yields:

Source Code
lib/prawn/document.rb, line 574
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.

Examples:

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"

Parameters:

  • y (Number)

Yields:

Source Code
lib/prawn/document.rb, line 557
557
def pad_top(y)
558
  move_down(y)
559
  yield
560
end

#page_countInteger

Number of pages in the document.

Examples:

pdf = Prawn::Document.new
pdf.page_count #=> 1
3.times { pdf.start_new_page }
pdf.page_count #=> 4

Returns:

  • (Integer)
Source Code
lib/prawn/document.rb, line 386
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

Parameters:

  • page_filter (:all, :odd, :even, Array<Number>, Range, Proc)
    • :all: repeats on every page
    • :odd: repeats on odd pages
    • :even: repeats on even pages
    • array: repeats on every page listed in the array
    • range: repeats on every page included in the range
    • lambda: yields page number and repeats for true return values
  • page_number (Integer)

Returns:

  • (Boolean)
Source Code
lib/prawn/document.rb, line 733
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.

Examples:

Draws a snazzy triangle

pdf.polygon [100,100], [100,200], [200,200]

Parameters:

  • points (Array<Array(Number, Number)>)

#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.

Examples:

pdf.rectangle [300, 300], 100, 200

Parameters:

  • point (Array(Number, Number))
  • width (Number)
  • height (Number)

#render(output = nil) ⇒ String

Renders the PDF document to string. Pass an open file descriptor to render to file.

Parameters:

  • output (#<<) (defaults to: nil)

Returns:

  • (String)
Source Code
lib/prawn/document.rb, line 456
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.

Examples:

pdf.render_file "foo.pdf"

Parameters:

  • filename (String)
Source Code
lib/prawn/document.rb, line 472
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.

Examples:

Prawn::Document.generate("repeat.pdf", skip_page_creation: true) do
  repeat :all do
    draw_text "ALLLLLL", at: bounds.top_left
  end

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

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

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

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

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

  10.times do
    start_new_page
    draw_text "A wonderful page", at: [400, 400]
  end

  repeat(:all, dynamic: true) do
    text page_number, at: [500, 0]
  end
end

Parameters:

  • page_filter (:all, :odd, :even, Array<Integer>, Range, Proc)

    Pages to draw the repeater content on.

    Available page filters are:

    • :all – repeats on every page.
    • :odd – repeats on odd pages.
    • :even – repeats on even pages.
    • Array of Integers – repeats on every page listed in the array.
    • Range – repeats on every page included in the range.
    • Proc – yields page number and repeats for true return values.
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :dynamic (Boolean) — default: false

    A dynamic repeater executes block on every matched page. A static repeater uses Stamp#stamp to prepare the content (runs the block once) and puts it on every matched page.

Source Code
lib/prawn/repeater.rb, line 77
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.

Examples:

save_graphics_state
rotate 30
text "rotated text"
restore_graphics_state

Rotating a rectangle around its upper-left corner

x = 300
y = 300
width = 150
height = 200
angle = 30
pdf.rotate(angle, :origin => [x, y]) do
  pdf.stroke_rectangle([x, y], width, height)
end

Parameters:

  • angle (Number)

    Angle in degrees.

  • options (Hash{Symbol => any}) (defaults to: {})

Options Hash (options):

  • :origin (Array(Number, Number))

    Rotation origin point. A block must be provided if specified.

Yields:

Raises:

#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.

Examples:

Draws a rounded filled in polygon

pdf.fill_and_stroke_rounded_polygon(
  10, [100, 250], [200, 300], [300, 250], [300, 150], [200, 100],
  [100, 150]
)

Parameters:

  • radius (Number)
  • points (Array<Array(Number, Number)>)

#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.

Examples:

pdf.rounded_rectangle [300, 300], 100, 200, 10

Parameters:

  • point (Array(Number, Number))
  • width (Number)
  • height (Number)
  • radius (Number)

#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.

Parameters:

  • radius (Number)
  • points (Array(Array(Number, Number), Array(Number, Number), Array(Number, Number)))

#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.

Yields:

Source Code
lib/prawn/font.rb, line 255
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.

Examples:

save_graphics_state
scale 1.5
text "scaled text"
restore_graphics_state

Scale a rectangle from its upper-left corner

x = 300
y = 300
width = 150
height = 200
factor = 1.5
pdf.scale(angle, :origin => [x, y]) do
  pdf.stroke_rectangle([x, y], width, height)
end

Parameters:

  • factor (Number)

    Scale factor.

  • options (Hash{Symbol => any}) (defaults to: {})

Options Hash (options):

  • :origin (Array(Number, Number))

    The point from which to scale. A block must be provided if specified.

Yields:

Raises:

#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).

Examples:

pdf.save_graphics_state do
  pdf.soft_mask do
    pdf.fill_color "444444"
    pdf.fill_polygon [0, 40], [60, 10], [120, 40], [60, 68]
  end
  pdf.fill_color '000000'
  pdf.fill_rectangle [0, 50], 120, 68
end

Yields:

  • Mask content.

#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.

Examples:

span(350, position: :center) do
  text "Here's some centered text in a 350 point column. " * 100
end

Parameters:

  • width (Number)

    The width of the column in PDF points

  • options (Hash{Symbol => any }) (defaults to: {})

Options Hash (options):

  • :position (:left, :center, :right, Number)

    position of the span relative to the page margins.

Yields:

Raises:

  • (ArgumentError)

    For unsupported :position value.

Source Code
lib/prawn/document/span.rb, line 31
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.

Examples:

pdf.create_stamp("my_stamp") {
  pdf.fill_circle([10, 15], 5)
  pdf.text("hello world", at: [20, 10])
}
pdf.stamp("my_stamp")

Parameters:

  • name (String)

Raises:

#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.

Examples:

pdf.create_stamp("circle") do
  pdf.fill_circle([0, 0], 25)
end
# draws a circle at 100, 100
pdf.stamp_at("circle", [100, 100])

Parameters:

  • name (String)
  • point (Array(Number, Number))

See Also:

  • for exceptions that might be raised.

#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.

Examples:

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)

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :margins (Hash{:left, :right, :top, :bottom => Number}, nil) — default: { left: 0, right: 0, top: 0, bottom: 0 }

    Page margins

  • :crop (Hash{:left, :right, :top, :bottom => Number}, nil) — default: PDF::Core::Page::ZERO_INDENTS

    Page crop box

  • :bleed (Hash{:left, :right, :top, :bottom => Number}, nil) — default: PDF::Core::Page::ZERO_INDENTS

    Page bleed box

  • :trims (Hash{:left, :right, :top, :bottom => Number}, nil) — default: PDF::Core::Page::ZERO_INDENTS

    Page trim box

  • :art_indents (Hash{:left, :right, :top, :bottom => Number}, nil) — default: PDF::Core::Page::ZERO_INDENTS

    Page art box indents.

  • :graphic_state (PDF::Core::GraphicState, nil) — default: nil

    Initial graphic state

  • :size (String, Array<Number>, nil) — default: 'LETTER'

    Page size. A string identifies a named page size defined in PDF::Core::PageGeometry. An array must be a two element array specifying width and height in points.

  • :layout (:portrait, :landscape, nil) — default: :portrait

    Page orientation.

Source Code
lib/prawn/document.rb, line 299
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.

Yields:

#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).

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :at (Array(Number, Number)) — default: [0, 0], origin of the bounding box

    Origin of the X and Y axes.

  • :width (Number) — default: width of the bounding box

    Length of the X axis.

  • :height (Number) — default: height of the bounding box

    Length of the Y axis.

  • :step_length (Number) — default: 100

    Length of the step between markers.

  • :negative_axes_length (Number) — default: 20

    Length of the negative parts of the axes.

  • :color (String, Array<Number>)

    The color of the axes and the text.

#stroke_boundsvoid Originally defined in module Graphics

This method returns an undefined value.

Draws and strokes a rectangle represented by the current bounding box.

#stroke_colorString, Array<Number> #stroke_color(color) ⇒ void Also known as: stroke_color= Originally defined in module Graphics::Color

Sets or returns the line stroking color.

Overloads:

  • #stroke_colorString, Array<Number>

    When called with no argument, it returns the current stroking color.

    Returns:

    • (String, Array<Number>)
  • #stroke_color(color) ⇒ void

    This method returns an undefined value.

    Sets the stroking color.

    Parameters:

    • color (String, Array<Number>)

      new stroking color:

      • In String form it should be a 6 digit HTML color code.

        pdf.stroke_color "f0ffc1"
        
      • If 4 arguments are provided, the color is assumed to be a CMYK value. Values range from 0 to 100.

        pdf.stroke_color 0, 99, 95, 0
        

#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.

Parameters:

  • origin (Array(Number, Number))
  • dest (Array(Number, Number))
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :bounds (Array(Array(Number, Number), Array(Number, Number)))

#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.

Parameters:

  • point (Array(Number, Number))
  • radius1 (Number)
  • radius2 (Number) (defaults to: radius1)

#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.

Overloads:

  • #fill_gradient(from, to, color1, color2, apply_margin_options: false) ⇒ void

    This method returns an undefined value.

    Set an axial (linear) stroke gradient.

    Parameters:

    • from (Array(Number, Number))

      Starting point of the gradient.

    • to (Array(Number, Number))

      ending point of the gradient.

    • color1 (Color)

      starting color of the gradient.

    • color2 (Color)

      ending color of the gradient.

    • apply_transformations (Boolean)

      (false) If set true, will transform the gradient’s co-ordinate space so it matches the current co-ordinate space of the document. This option will be the default from Prawn v3, and is default true if you use the all-keyword version of this method. The default for the positional arguments version (this one), false, will mean if you (for example) scale your document by 2 and put a gradient inside, you will have to manually multiply your co-ordinates by 2 so the gradient is correctly positioned.

  • #fill_gradient(from, r1, to, r2, color1, color2, apply_margin_options: false) ⇒ void

    This method returns an undefined value.

    Set a radial stroke gradient.

    Parameters:

    • from (Array(Number, Number))

      Starting point of the gradient.

    • r1 (Number)

      Radius of the starting circle of a radial gradient. The circle is centered at from.

    • to (Array(Number, Number))

      Ending point of the gradient.

    • r2 (Number)

      Radius of the ending circle of a radial gradient. The circle is centered at to.

    • color1 (Color)

      Starting color.

    • color2 (Color)

      Ending color.

    • apply_transformations (Boolean)

      (false) If set true, will transform the gradient’s co-ordinate space so it matches the current co-ordinate space of the document. This option will be the default from Prawn v3, and is default true if you use the all-keyword version of this method. The default for the positional arguments version (this one), false, will mean if you (for example) scale your document by 2 and put a gradient inside, you will have to manually multiply your co-ordinates by 2 so the gradient is correctly positioned.

  • #fill_gradient(from: , to: , r1: nil, r2: nil, stops: , apply_margin_options: true) ⇒ void

    This method returns an undefined value.

    Set the stroke gradient.

    Examples:

    Draw a horizontal axial gradient that starts at red on the left and ends at blue on the right

    stroke_gradient from: [0, 0], to: [100, 0], stops: ['ff0000', '0000ff']

    Draw a horizontal radial gradient that starts at red, is green 80% through, and finishes blue

    stroke_gradient from: [0, 0], r1: 0, to: [100, 0], r2: 180,
      stops: { 0 => 'ff0000', 0.8 => '00ff00', 1 => '0000ff' }

    Parameters:

    • from (Array(Number, Number)) (defaults to: )

      Starting point of the gradient.

    • r1 (Number, nil) (defaults to: nil)

      Radius of the starting circle of a radial gradient. The circle is centered at from. If omitted a linear gradient will be produced.

    • to (Array(Number, Number)) (defaults to: )

      Ending point of the gradient.

    • r2 (Number, nil) (defaults to: nil)

      Radius of the ending circle of a radial gradient. The circle is centered at to.

    • stops (Array<Color>, Hash{Number => Color}) (defaults to: )

      Color stops. Each stop is either just a color, in which case the stops will be evenly distributed across the gradient, or a hash where the key is a position between 0 and 1 indicating what distance through the gradient the color should change, and the value is a color.

    • apply_transformations (Boolean)

      (true) If set true, will transform the gradient’s co-ordinate space so it matches the current co-ordinate space of the document. This option will be the default from Prawn v3, and is default true if you use the all-keyword version of this method (this one). The default for the old arguments format, false, will mean if you (for example) scale your document by 2 and put a gradient inside, you will have to manually multiply your co-ordinates by 2 so the gradient is correctly positioned.

#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.

Parameters:

  • x1 (Number)
  • x2 (Number)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :at (Number)

#stroke_horizontal_rulevoid 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.

Overloads:

  • #line(point1, point2) ⇒ void

    This method returns an undefined value.

    Parameters:

    • point1 (Array(Number, Number))
    • point2 (Array(Number, Number))
  • #line(x1, y1, x2, y2) ⇒ void

    This method returns an undefined value.

    Parameters:

    • x1 (Number)
    • y1 (Number)
    • x2 (Number)
    • y2 (Number)

#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.

Parameters:

  • point (Array(Number, Number))
  • width (Number)
  • height (Number)

#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.

Parameters:

  • radius (Number)
  • points (Array<Array(Number, Number)>)

#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.

Parameters:

  • point (Array(Number, Number))
  • width (Number)
  • height (Number)
  • radius (Number)

#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.

Parameters:

  • y1 (Number)
  • y2 (Number)
  • params (Hash)

Options Hash (params):

  • :at (Number)

#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.

Parameters:

  • string (String)
  • options (Hash{Symbol => any}) (defaults to: {})
  • option (Hash)

    a customizable set of options

Options Hash (options):

  • :inline_format (Boolean)

    If true, then the string parameter is interpreted as a HTML-esque string that recognizes the following tags (assuming the default text formatter is used):

    • <b></b> — bold style.
    • <i></i> — italic style.
    • <u></u> — underline.
    • <strikethrough></strikethrough> — strikethrough.
    • <sub></sub> — subscript.
    • <sup></sup> — superscript.
    • <font></font> — with the following attributes (using double or single quotes):
      • name="Helvetica" — the font. The font name must be an AFM font with the desired faces or must be a font that is already registered using Document#font_families.
      • size="24" — attribute for setting size.
      • character_spacing="2.5" — character spacing.
    • <color></color> — text color
      • rgb="ffffff" or rgb="#ffffff" — RGB color
      • c="100" m="100" y="100" k="100" — CMYK color
    • <link></link> - link, with the following attributes:
      • href="http://example.com" — an external link. Note that you must explicitly underline and color using the appropriate tags if you which to draw attention to the link.
  • :kerning (Boolean) — default: value of document.default_kerning?

    Whether or not to use kerning (if it is available with the current font).

  • :size (Number) — default: current ofnt size

    The font size to use.

  • :color (Color)
  • :character_spacing (Number) — default: 0

    The amount of space to add to or remove from the default character spacing.

  • :style (Symbol) — default: current style

    The style to use. The requested style must be part of the current font family.

  • :indent_paragraphs (Number)

    The amount to indent the first line of each paragraph. Omit this option if you do not want indenting.

  • :direction (:ltr, :rtl) — default: value of document.text_direction

    Direction of the text.

  • :fallback_fonts (Array<String>)

    An array of font names. Each name must be the name of an AFM font or the name that was used to register a family of TTF fonts (see Document#font_families). If present, then each glyph will be rendered using the first font that includes the glyph, starting with the current font and then moving through :fallback_fonts.

  • :valign (:top, :center, :bottom) — default: :top

    Vertical alignment within the bounding box.

  • :leading (Object) — default: Number

    (value of document.default_leading) Additional space between lines.

  • :final_gap (Boolean) — default: true

    If true, then the space between each line is included below the last line; otherwise, Document#y is placed just below the descender of the last line printed.

  • :mode (Symbol) — default: :fill

    The text rendering mode to use. Use this to specify if the text should render with the fill color, stroke color or both.

    • :fill - fill text (default)
    • :stroke - stroke text
    • :fill_stroke - fill, then stroke text
    • :invisible - invisible text
    • :fill_clip - fill text then add to path for clipping
    • :stroke_clip - stroke text then add to path for clipping
    • :fill_stroke_clip - fill then stroke text, then add to path for clipping
    • :clip - add text to path for clipping

Raises:

  • (ArgumentError)

    if :at option included

  • (Prawn::Errrors::CannotFit)

    if not wide enough to print any text

See Also:

  • for a list of valid text rendering modes.

#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.

Parameters:

  • string (String)
  • options (Hash{Symbol => any}) (defaults to: {})
  • option (Hash)

    a customizable set of options

Options Hash (options):

  • :kerning (Boolean) — default: value of document.default_kerning?

    Whether or not to use kerning (if it is available with the current font).

  • :size (Number) — default: current font size

    The font size to use.

  • :character_spacing (Number) — default: 0

    The amount of space to add to or remove from the default character spacing.

  • :disable_wrap_by_char (Boolean) — default: false

    Whether or not to prevent mid-word breaks when text does not fit in box.

  • :mode (Symbol) — default: :fill

    The text rendering mode. See documentation for Document#text_rendering_mode for a list of valid options.

  • :width (Number) — default: bounds.right - at[0]

    The width of the box.

  • :height (Number) — default: default_height()

    The height of the box.

  • :direction (:ltr, :rtl) — default: value of document.text_direction

    Direction of the text (left-to-right or right-to-left).

  • :fallback_fonts (Array<String>)

    An array of font names. Each name must be the name of an AFM font or the name that was used to register a family of external fonts (see Document#font_families). If present, then each glyph will be rendered using the first font that includes the glyph, starting with the current font and then moving through :fallback_fonts.

  • :align (:left, :center, :right, :justify) — default: :left if direction is :ltr, :right if direction is :rtl

    Alignment within the bounding box.

  • :valign (:top, :center, :bottom) — default: :top

    Vertical alignment within the bounding box.

  • :rotate (Number)

    The angle to rotate the text.

  • :rotate_around (Object)

    [:center, :upper_left, :upper_right, :lower_right, :lower_left] (:upper_left) The point around which to rotate the text.

  • :leading (Number) — default: value of document.default_leading

    Additional space between lines.

  • :single_line (Boolean) — default: false

    If true, then only the first line will be drawn.

  • :overflow (:truncate, :shrink_to_fit, :expand) — default: :truncate

    This controls the behavior when the amount of text exceeds the available space.

  • :min_font_size (Number) — default: 5

    The minimum font size to use when :overflow is set to :shrink_to_fit (that is the font size will not be reduced to less than this value, even if it means that some text will be cut off).

Returns:

  • (String)

    Any text that did not print under the current settings.

Raises:

#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

Parameters:

  • matrix (Array(Number, Number, Number, Number, Number, Number))

    Transformation matrix.

    The six elements correspond to the following elements of the transformation matrix:

    a b 0
    c d 0
    e f 0
    

Yields:

#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.

Examples:

Move the text up and over 10

save_graphics_state
translate(10, 10)
text "scaled text"
restore_graphics_state

draw a rectangle with its upper-left corner at x + 10, y + 10

x = 300
y = 300
width = 150
height = 200
pdf.translate(10, 10) do
  pdf.stroke_rectangle([x, y], width, height)
end

Parameters:

  • x (Number)
  • y (Number)

Yields:

#transparent(opacity, stroke_opacity = opacity) { ... } ⇒ void Originally defined in module Graphics::Transparency

This method returns an undefined value.

Set opacity.

Examples:

Both the fill and stroke will be at 50% opacity.

pdf.transparent(0.5) do
  pdf.text("hello world")
  pdf.fill_and_stroke_circle([x, y], 25)
end

The fill will be at 50% opacity, but the stroke will be at 75% opacity.

pdf.transparent(0.5, 0.75) do
  pdf.text("hello world")
  pdf.fill_and_stroke_circle([x, y], 25)
end

Parameters:

  • opacity (Number)

    Fill opacity. Clipped to the 0.0 to 1.0 range.

  • stroke_opacity (Number) (defaults to: opacity)

    Stroke opacity. Clipped to the 0.0 to 1.0 range.

Yields:

#undashvoid 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.

Examples:

Draw a line from [25, 100] to [25, 300]

vertical_line 100, 300, at: 25

Parameters:

  • y1 (Number)
  • y2 (Number)
  • params (Hash)

Options Hash (params):

  • :at (Number)

#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.

Parameters:

  • string (String)
  • options (Hash{Symbol => any}) (defaults to: {})

Options Hash (options):

  • :inline_format (Boolean) — default: false
  • :kerning (Boolean) — default: false
  • :style (Symbol)

Returns:

  • (Number)
Source Code
lib/prawn/font.rb, line 150
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