Prawn: by Example
Prawn: by Example
by example
Last Update: 2014-07-27
Prawn Version: 1.2.0
git commit: 730d866
How to read this manual
This manual is a collection of examples categorized by theme and organized from the least to the
most complex. While it covers most of the common use cases it is not a comprehensive guide.
The best way to read it depends on your previous knowledge of Prawn and what you need to
accomplish.
If you are beginning with Prawn the first chapter will teach you the most basic concepts and how to
create pdf documents. For an overview of the other features each chapter beyond the first either
has a Basics section (which offer enough insight on the feature without showing all the advanced
stuff you might never use) or is simple enough with only a few examples.
Once you understand the basics you might want to come back to this manual looking for examples
that accomplish tasks you need.
Advanced users are encouraged to go beyond this manual and read the source code directly if any
doubt is not directly covered on this manual.
Reading the examples
The title of each example is the relative path from the Prawn source manual/ folder.
The first body of text is the introductory text for the example. Generaly it is a short description of
the features illustrated by the example.
Next comes the example source code block in fixed width font.
Most of the example snippets illustrate features that alter the page in place. The effect of these
snippets is shown right below a dashed line. If it doesn't make sense to evaluate the snippet inline,
a box with the link for the example file is shown instead.
Note that the stroke_axis method, used occasionally in the manual, is not part of standard
Prawn and is used for demonstrative purposes. It is defined in this file:
https://github.com/prawnpdf/prawn/blob/master/manual/example_helper.rb
Basic concepts
This chapter covers the minimum amount of functionality you'll need to start using Prawn.
If you are new to Prawn this is the first chapter to read. Once you are comfortable with the
concepts shown here you might want to check the Basics section of the Graphics, Bounding Box
and Text sections.
The examples show:
How to create new pdf documents in every possible way
Where the origin for the document coordinates is. What are Bounding Boxes and how they
interact with the origin
How the cursor behaves
How to start new pages
What the base unit for measurement and coordinates is and how to use other convenient
measures
basic_concepts/creation.rb
There are three ways to create a PDF Document in Prawn: creating a new Prawn::Document
instance, or using the Prawn::Document.generate method with and without block arguments.
The following snippet showcase each way by creating a simple document with some text drawn.
When we instantiate the Prawn::Document object the actual pdf document will only be created
after we call render_file.
The generate method will render the actual pdf object after exiting the block. When we use it
without a block argument the provided block is evaluated in the context of a newly created
Prawn::Document instance. When we use it with a block argument a Prawn::Document
instance is created and passed to the block.
The generate method without block arguments requires less typing and defines and renders the
pdf document in one shot. Almost all of the examples are coded this way.
Assignment Implicit Block Explicit Block
#Assignment
pdf=Prawn::Document.new
pdf.text"HelloWorld"
pdf.render_file"assignment.pdf"
#ImplicitBlock
Prawn::Document.generate("implicit.pdf")do
text"HelloWorld"
end
#ExplicitBlock
Prawn::Document.generate("explicit.pdf")do|pdf|
pdf.text"HelloWorld"
end
This code snippet was not evaluated inline. You may see its output by running the example file located here:
http://github.com/prawnpdf/prawn/tree/master/manual/basic_concepts/creation.rb
basic_concepts/origin.rb
This is the most important concept you need to learn about Prawn:
PDF documents have the origin [0,0] at the bottom-left corner of the page.
A bounding box is a structure which provides boundaries for inserting content. A bounding box
also has the property of relocating the origin to its relative bottom-left corner. However, be aware
that the location specified when creating a bounding box is its top-left corner, not bottom-left
(hence the [100, 300] coordinates below).
Even if you never create a bounding box explictly, each document already comes with one called
the margin box. This initial bounding box is the one responsible for the document margins.
So practically speaking the origin of a page on a default generated document isn't the absolute
bottom left corner but the bottom left corner of the margin box.
The following snippet strokes a circle on the margin box origin. Then strokes the boundaries of a
bounding box and a circle on its origin.
stroke_axis
stroke_circle[0,0],10
bounding_box([100,300],:width=>300,:height=>200)do
stroke_bounds
stroke_circle[0,0],10
end
100 200 300 400 500
100
200
300
basic_concepts/cursor.rb
We normally write our documents from top to bottom and it is no different with Prawn. Even if the
origin is on the bottom left corner we still fill the page from the top to the bottom. In other words the
cursor for inserting content starts on the top of the page.
Most of the functions that insert content on the page will start at the current cursor position and
proceed to the bottom of the page.
The following snippet shows how the cursor behaves when we add some text to the page and
demonstrates some of the helpers to manage the cursor position. The cursor method returns the
current cursor position.
stroke_axis
text"thecursorishere:#{cursor}"
text"nowitishere:#{cursor}"
move_down200
text"onthefirstmovethecursorwentdownto:#{cursor}"
move_up100
text"onthesecondmovethecursorwentupto:#{cursor}"
move_cursor_to50
text"onthelastmovethecursorwentdirectlyto:#{cursor}"
100 200 300 400 500
100
200
300
the cursor is here: 383.9795
now it is here: 370.10749999999996
on the first move the cursor went down to: 156.23549999999994
on the second move the cursor went up to: 242.36349999999993
on the last move the cursor went directly to: 50.0
basic_concepts/other_cursor_helpers.rb
Another group of helpers for changing the cursor position are the pad methods. They accept a
numeric value and a block. pad will use the numeric value to move the cursor down both before
and after the block content. pad_top will only move the cursor before the block while
pad_bottom will only move after.
float is a method for not changing the cursor. Pass it a block and the cursor will remain on the
same place when the block returns.
stroke_horizontal_rule
pad(20){text"Textpaddedbothbeforeandafter."}
stroke_horizontal_rule
pad_top(20){text"Textpaddedonthetop."}
stroke_horizontal_rule
pad_bottom(20){text"Textpaddedonthebottom."}
stroke_horizontal_rule
move_down30
text"Textwrittenbeforethefloatblock."
floatdo
move_down30
bounding_box([0,cursor],:width=>200)do
text"Textwritteninsidethefloatblock."
stroke_bounds
end
end
text"Textwrittenafterthefloatblock."
Text padded both before and after.
Text padded on the top.
Text padded on the bottom.
Text written before the float block.
Text written inside the float block.
Text written after the float block.
basic_concepts/adding_pages.rb
A PDF document is a collection of pages. When we create a new document be it with
Document.new or on a Document.generate block one initial page is created for us.
Some methods might create new pages automatically like text which will create a new page
whenever the text string cannot fit on the current page.
But what if you want to go to the next page by yourself? That is easy.
Just use the start_new_page method and a shiny new page will be created for you just like in
the following snippet.
text"Wearestillontheinitialpageforthisexample.NowI'llask"+
"Prawntogentlystartanewpage.Pleasefollowmetothenextpage."
start_new_page
text"See.We'veleftthepreviouspagebehind."
We are still on the initial page for this example. Now I'll ask Prawn to gently start a new page. Please
follow me to the next page.
See. We've left the previous page behind.
basic_concepts/measurement.rb
The base unit in Prawn is the PDF Point. One PDF Point is equal to 1/72 of an inch.
There is no need to waste time converting this measures. Prawn provides helpers for converting
from other measurements to PDF Points.
Just require "prawn/measurement_extensions" and it will mix some helpers onto
Numeric for converting common measurement units to PDF Points.
require"prawn/measurement_extensions"
[:mm,:cm,:dm,:m,:in,:yd,:ft].eachdo|measurement|
text"1#{measurement}inPDFPoints:#{1.send(measurement)}pt"
move_down5.mm
end
1 mm in PDF Points: 2.834645669291339 pt
1 cm in PDF Points: 28.34645669291339 pt
1 dm in PDF Points: 283.46456692913387 pt
1 m in PDF Points: 2834.645669291339 pt
1 in in PDF Points: 72 pt
1 yd in PDF Points: 2592 pt
1 ft in PDF Points: 864 pt
Graphics
Here we show all the drawing methods provided by Prawn. Use them to draw the most beautiful
imaginable things.
Most of the content that you'll add to your pdf document will use the graphics package. Even text is
rendered on a page just like a rectangle so even if you never use any of the shapes described here
you should at least read the basic examples.
The examples show:
All the possible ways that you can fill or stroke shapes on a page
How to draw all the shapes that Prawn has to offer from a measly line to a mighty polygon or
ellipse
The configuration options for stroking lines and filling shapes
How to apply transformations to your drawing space
graphics/helper.rb
To produce this manual we use the stroke_axis helper method within the examples.
stroke_axis prints the x and y axis for the current bounding box with markers in 100
increments. The defaults can be changed with various options.
Note that the examples define a custom :height option so that only the example canvas is used
(as seen with the output of the first line of the example code).
stroke_axis
stroke_axis(:at=>[70,70],:height=>200,:step_length=>50,
:negative_axes_length=>5,:color=>'0000FF')
stroke_axis(:at=>[140,140],:width=>200,:height=>cursor.to_i-140,
:step_length=>20,:negative_axes_length=>40,:color=>'FF00')
100 200 300 400 500
100
200
300
400
500
50 100 150 200 250 300 350 400 450
50
100
150
200
20 40 60 80 100 120 140 160 180 200
20
40
60
80
100
120
140
160
180
200
220
240
260
280
300
320
340
360
380
graphics/fill_and_stroke.rb
There are two drawing primitives in Prawn: fill and stroke.
These are the methods that actually draw stuff on the document. All the other drawing shapes like
rectangle, circle or line_to define drawing paths. These paths need to be either stroked or
filled to gain form on the document.
Calling these methods without a block will act on the drawing path that has been defined prior to
the call.
Calling with a block will act on the drawing path set within the block.
Most of the methods which define drawing paths have methods of the same name starting with
stroke_ and fill_ which create the drawing path and then stroke or fill it.
stroke_axis
#Noblock
line[0,200],[100,150]
stroke
rectangle[0,100],100,100
fill
#Withblock
stroke{line[200,200],[300,150]}
fill{rectangle[200,100],100,100}
#Methodhook
stroke_line[400,200],[500,150]
fill_rectangle[400,100],100,100
100 200 300 400 500
100
200
graphics/lines_and_curves.rb
Prawn supports drawing both lines and curves starting either at the current position, or from a
specified starting position.
line_to and curve_to set the drawing path from the current drawing position to the specified
point. The initial drawing position can be set with move_to. They are useful when you want to
chain successive calls because the drawing position will be set to the specified point afterwards.
line and curve set the drawing path between the two specified points.
Both curve methods define a Bezier curve bounded by two aditional points provided as the
:bounds param.
stroke_axis
#line_toandcurve_to
strokedo
move_to0,0
line_to100,100
line_to0,100
curve_to[150,250],:bounds=>[[20,200],[120,200]]
curve_to[200,0],:bounds=>[[150,200],[450,10]]
end
#lineandcurve
strokedo
line[300,200],[400,50]
curve[500,0],[400,200],:bounds=>[[600,300],[300,390]]
end
100 200 300 400 500
100
200
graphics/common_lines.rb
Prawn provides helpers for drawing some commonly used lines:
vertical_line and horizontal_line do just what their names imply. Specify the start and
end point at a fixed coordinate to define the line.
horizontal_rule draws a horizontal line on the current bounding box from border to border,
using the current y position.
stroke_axis
stroke_color"ff0000"
strokedo
#justlowerthecurrentyposition
move_down50
horizontal_rule
vertical_line100,300,:at=>50
horizontal_line200,500,:at=>150
end
100 200 300 400 500
100
200
300
400
graphics/rectangle.rb
To draw a rectangle, just provide the upper-left corner, width and height to the rectangle
method.
There's also rounded_rectangle. Just provide an additional radius value for the rounded
corners.
stroke_axis
strokedo
rectangle[100,300],100,200
rounded_rectangle[300,300],100,200,20
end
100 200 300 400 500
100
200
300
400
500
graphics/polygon.rb
Drawing polygons in Prawn is easy, just pass a sequence of points to one of the polygon family of
methods.
Just like rounded_rectangle we also have rounded_polygon. The only difference is the
radius param comes before the polygon points.
stroke_axis
#Triangle
stroke_polygon[50,200],[50,300],[150,300]
#Hexagon
fill_polygon[50,150],[150,200],[250,150],
[250,50],[150,0],[50,50]
#Pentagram
pentagon_points=[500,100],[430,5],[319,41],[319,159],[430,195]
pentagram_points=[0,2,4,1,3].map{|i|pentagon_points[i]}
stroke_rounded_polygon(20,*pentagram_points)
100 200 300 400 500
100
200
300
400
graphics/circle_and_ellipse.rb
To define a circle all you need is the center point and the radius.
To define an ellipse you provide the center point and two radii (or axes) values. If the second
radius value is ommitted, both radii will be equal and you will end up drawing a circle.
stroke_axis
stroke_circle[100,300],100
fill_ellipse[200,100],100,50
fill_ellipse[400,100],50
100 200 300 400 500
100
200
300
400
500
graphics/line_width.rb
The line_width= method sets the stroke width for subsequent stroke calls.
Since Ruby assumes that an unknown variable on the left hand side of an assignment is a local
temporary, rather than a setter method, if you are using the block call to
Prawn::Document.generate without passing params you will need to call line_width on
self.
stroke_axis
y=250
3.timesdo|i|
casei
when0thenline_width=10#Thiscallwillhavenoeffect
when1thenself.line_width=10
when2thenself.line_width=25
end
strokedo
horizontal_line50,150,:at=>y
rectangle[275,y+25],50,50
circle[500,y],25
end
y-=100
end
100 200 300 400 500
100
200
300
graphics/stroke_cap.rb
The cap style defines how the edge of a line or curve will be drawn. There are three types: :butt
(the default), :round and :projecting_square
The difference is better seen with thicker lines. With :butt lines are drawn starting and ending at
the exact points provided. With both :round and :projecting_square the line is projected
beyond the start and end points.
Just like line_width= the cap_style= method needs an explicit receiver to work.
stroke_axis
self.line_width=25
[:butt,:round,:projecting_square].each_with_indexdo|cap,i|
self.cap_style=cap
y=250-i*100
stroke_horizontal_line100,300,:at=>y
stroke_circle[400,y],15
end
100 200 300 400 500
100
200
300
400
graphics/stroke_join.rb
The join style defines how the intersection between two lines is drawn. There are three types:
:miter (the default), :round and :bevel
Just like cap_style, the difference between styles is better seen with thicker lines.
stroke_axis
self.line_width=25
[:miter,:round,:bevel].each_with_indexdo|style,i|
self.join_style=style
y=200-i*100
strokedo
move_to(100,y)
line_to(200,y+100)
line_to(300,y)
end
stroke_rectangle[400,y+75],50,50
end
100 200 300 400 500
100
200
300
400
graphics/stroke_dash.rb
This sets the dashed pattern for lines and curves. The (dash) length defines how long each dash
will be.
The :space option defines the length of the space between the dashes.
The :phase option defines the start point of the sequence of dashes and spaces.
Complex dash patterns can be specified by using an array with alternating dash/gap lengths for
the first parameter (note that the :space option is ignored in this case).
stroke_axis
dash([1,2,3,2,1,5],:phase=>6)
stroke_horizontal_line50,500,:at=>230
dash([1,2,3,4,5,6,7,8])
stroke_horizontal_line50,500,:at=>220
base_y=210
24.timesdo|i|
length=(i/4)+1
space=length#spacebetweendashessamelengthasdash
phase=0#startwithdash
casei%4
when0thenbase_y-=5
when1thenphase=length#startwithspacebetweendashes
when2thenspace=length*0.5#spacebetweendasheshalfaslongasdash
when3
space=length*0.5#spacebetweendasheshalfaslongasdash
phase=length#startwithspacebetweendashes
end
base_y-=5
dash(length,:space=>space,:phase=>phase)
stroke_horizontal_line50,500,:at=>base_y-(2*i)
end
100 200 300 400 500
100
200
graphics/color.rb
We can change the stroke and fill colors providing an HTML rgb 6 digit color code string
("AB1234") or 4 values for CMYK.
stroke_axis
#FillwithYellowusingRGB
fill_color"FFFFCC"
fill_polygon[50,150],[150,200],[250,150],
[250,50],[150,0],[50,50]
#StrokewithPurpleusingCMYK
stroke_color50,100,0,0
stroke_rectangle[300,300],200,100
#Bothtogether
fill_and_stroke_circle[400,100],50
100 200 300 400 500
100
200
300
400
graphics/gradients.rb
Note that because of the way PDF renders radial gradients in order to get solid fill your start circle
must be fully inside your end circle. Otherwise you will get triangle fill like illustrated in the example
below.
stroke_axis
self.line_width=10
fill_gradient[50,300],[150,200],'ff0000','0000ff'
fill_rectangle[50,300],100,100
stroke_gradient[200,200],[300,300],'00ffff','ffff00'
stroke_rectangle[200,300],100,100
fill_gradient[350,300],[450,200],'ff0000','0000ff'
stroke_gradient[350,200],[450,300],'00ffff','ffff00'
fill_and_stroke_rectangle[350,300],100,100
fill_gradient[100,100],0,[100,100],70.71,'ff0000','0000ff'
fill_rectangle[50,150],100,100
stroke_gradient[250,100],45,[250,100],70.71,'00ffff','ffff00'
stroke_rectangle[200,150],100,100
stroke_gradient[400,100],45,[400,100],70.71,'00ffff','ffff00'
fill_gradient[400,100],0,[400,100],70.71,'ff0000','0000ff'
fill_and_stroke_rectangle[350,150],100,100
fill_gradient[500,300],15,[500,50],0,'ff0000','0000ff'
fill_rectangle[485,300],30,250
100 200 300 400 500
100
200
300
graphics/transparency.rb
Although the name of the method is transparency, what we are actually setting is the opacity for
fill and stroke. So 0 means completely transparent and 1.0 means completely opaque
You may call it providing one or two values. The first value sets fill opacity and the second value
sets stroke opacity. If the second value is omitted fill and stroke will have the same opacity.
stroke_axis
self.line_width=5
fill_color"ff0000"
fill_rectangle[0,100],500,100
fill_color"000000"
stroke_color"ffffff"
base_x=100
[[0.5,1],0.5,[1,0.5]].eachdo|args|
transparent(*args)do
fill_circle[base_x,100],50
stroke_rectangle[base_x-20,100],40,80
end
base_x+=150
end
100 200 300 400 500
100
200
300
graphics/soft_masks.rb
Soft masks are user for more complex alpha channel manipulations. You can use arbitrary drawing
functions for creation of soft masks. The resulting alpha channel is made of greyscale version of
the drawing (luminosity channel to be precise). So while you can use any combination of colors for
soft masks it's easier to use greyscales. Black will result in full transparency and white will make
region fully opaque.
Soft mask is a part of page graphic state. So if you want to apply soft mask only to a part of page
you need to enclose drawing instructions in save_graphics_state block.
save_graphics_statedo
soft_maskdo
0.upto15do|i|
fill_color0,0,0,100.0/16.0*(15-i)
fill_circle[75+i*25,100],60
end
end
fill_color'009ddc'
fill_rectangle[0,60],600,20
fill_color'963d97'
fill_rectangle[0,80],600,20
fill_color'e03a3e'
fill_rectangle[0,100],600,20
fill_color'f5821f'
fill_rectangle[0,120],600,20
fill_color'fdb827'
fill_rectangle[0,140],600,20
fill_color'61bb46'
fill_rectangle[0,160],600,20
end
graphics/fill_rules.rb
Prawn's fill operators (fill and fill_and_stroke both accept a :fill_rule option. These
rules determine which parts of the page are counted as "inside" vs. "outside" the path. There are
two fill rules:
* :nonzero_winding_number (default): a point is inside the path if a ray from that point to
infinity crosses a nonzero "net number" of path segments, where path segments intersecting in
one direction are counted as positive and those in the other direction negative.
* :even_odd: A point is inside the path if a ray from that point to infinity crosses an odd number of
path segments, regardless of direction.
The differences between the fill rules only come into play with complex paths; they are identical for
simple shapes.
pentagram=[[181,95],[0,36],[111,190],[111,0],[0,154]]
stroke_color'ff0000'
line_width2
text_box"NonzeroWindingNumber",:at=>[50,215],:width=>170,
:align=>:center
polygon(*pentagram.map{|x,y|[x+50,y]})
fill_and_stroke
text_box"Even-Odd",:at=>[330,215],:width=>170,:align=>:center
polygon(*pentagram.map{|x,y|[x+330,y]})
fill_and_stroke(:fill_rule=>:even_odd)
Nonzero Winding Number Even-Odd
graphics/rotate.rb
This transformation is used to rotate the user space. Give it an angle and an :origin point about
which to rotate and a block. Everything inside the block will be drawn with the rotated coordinates.
The angle is in degrees.
If you omit the :origin option the page origin will be used.
stroke_axis
fill_circle[250,200],2
12.timesdo|i|
rotate(i*30,:origin=>[250,200])do
stroke_rectangle[350,225],100,50
draw_text"Rotated#{i*30}",:size=>10,:at=>[360,205]
end
end
100 200 300 400 500
100
200
300
400
Rotated 0
R
o
t
a
t
e
d
3
0
R
o
t
a
t
e
d
6
0
R
o
t
a
t
e
d
9
0
R
o
t
a
t
e
d
1
2
0
R
o
t
a
t
e
d
1
5
0
R o t a t e d 1 8 0
R
o
t
a
t
e
d
2
1
0
R
o
t
a
t
e
d
2
4
0
R
o
t
a
t
e
d
2
7
0
R
o
t
a
t
e
d
3
0
0
R
o
t
a
t
e
d
3
3
0
graphics/translate.rb
This transformation is used to translate the user space. Just provide the x and y coordinates for
the new origin.
stroke_axis
1.upto(3)do|i|
x=i*50
y=i*100
translate(x,y)do
#Drawapointontheneworigin
fill_circle[0,0],2
draw_text"Neworiginaftertranslationto[#{x},#{y}]",
:at=>[5,-2],:size=>8
stroke_rectangle[100,75],100,50
text_box"Topleftcornerat[100,75]",
:at=>[110,65],:width=>80,:size=>8
end
end
100 200 300 400 500
100
200
300
400
New origin after translation to [50, 100]
Top left corner at
[100,75]
New origin after translation to [100, 200]
Top left corner at
[100,75]
New origin after translation to [150, 300]
Top left corner at
[100,75]
graphics/scale.rb
This transformation is used to scale the user space. Give it an scale factor and an :origin point
and everything inside the block will be scaled using the origin point as reference.
If you omit the :origin option the page origin will be used.
stroke_axis
width=100
height=50
x=50
y=200
stroke_rectangle[x,y],width,height
text_box"referencerectangle",:at=>[x+10,y-10],:width=>width-20
scale(2,:origin=>[x,y])do
stroke_rectangle[x,y],width,height
text_box"rectanglescaledfromupper-leftcorner",
:at=>[x,y-height-5],:width=>width
end
x=350
stroke_rectangle[x,y],width,height
text_box"referencerectangle",:at=>[x+10,y-10],:width=>width-20
scale(2,:origin=>[x+width/2,y-height/2])do
stroke_rectangle[x,y],width,height
text_box"rectanglescaledfromcenter",
:at=>[x,y-height-5],:width=>width
end
100 200 300 400 500
100
200
reference
rectangle
rectangle scaled
from upper-left
corner
reference
rectangle
rectangle scaled
from center
Text
This is probably the feature people will use the most. There is no shortage of options when it
comes to text. You'll be hard pressed to find a use case that is not covered by one of the text
methods and configurable options.
The examples show:
Text that flows from page to page automatically starting new pages when necessary
How to use text boxes and place them on specific positions
What to do when a text box is too small to fit its content
Flowing text in columns
How to change the text style configuring font, size, alignment and many other settings
How to style specific portions of a text with inline styling and formatted text
How to define formatted callbacks to reuse common styling definitions
How to use the different rendering modes available for the text methods
How to create your custom text box extensions
How to use external fonts on your pdfs
What happens when rendering text in different languages
text/free_flowing_text.rb
Text rendering can be as simple or as complex as you want.
This example covers the most basic method: text. It is meant for free flowing text. The provided
string will flow according to the current bounding box width and height. It will also flow onto the
next page if the bottom of the bounding box is reached.
The text will start being rendered on the current cursor position. When it finishes rendering, the
cursor is left directly below the text.
This example also shows text flowing across pages following the margin box and other bounding
boxes.
move_cursor_to50
text"Thistextwillflowtothenextpage."*20
y_position=cursor-50
bounding_box([0,y_position],:width=>200,:height=>150)do
transparent(0.5){stroke_bounds}
text"Thistextwillflowalongthisboundingboxwecreatedforit."*5
end
bounding_box([300,y_position],:width=>200,:height=>150)do
transparent(0.5){stroke_bounds}#Thiswillstrokeononepage
text"Nowlookwhathappenswhenthefreeflowingtextreachestheend"+
"ofaboundingboxthatisnarrowerthanthemarginbox."+
"."*200+
"Itcontinuesonthenextpageasifthepreviousboundingbox"+
"wascloned.Ifwewantittohavethesameborderastheoneon"+
"thepreviouspagewewillneedtostroketheboundariesagain."
transparent(0.5){stroke_bounds}#Andthiswillstrokeonthenext
end
move_cursor_to200
span(350,:position=>:center)do
text"Spanisadifferentkindofboundingboxasitletsthetext"+
"flowgracefullyontothenextpage.Itdoesn'tmatterifthetext"+
"startedonthemiddleofthepreviouspage,whenitflowstothe"+
"nextpageitwillstartatthebeginning."+"_"*500+
"Itoldyouitwouldstartonthebeginningofthispage."
end
This text will flow to the next page. This text will flow to the next page. This text will flow to the next
page. This text will flow to the next page. This text will flow to the next page. This text will flow to the
next page. This text will flow to the next page. This text will flow to the next page. This text will flow to
the next page. This text will flow to the next page. This text will flow to the next page. This text will flow
to the next page. This text will flow to the next page. This text will flow to the next page. This text will
flow to the next page. This text will flow to the next page. This text will flow to the next page. This text
will flow to the next page. This text will flow to the next page. This text will flow to the next page.
This text will flow along this bounding
box we created for it. This text will
flow along this bounding box we
created for it. This text will flow along
this bounding box we created for it.
This text will flow along this bounding
box we created for it. This text will
flow along this bounding box we
created for it.
Now look what happens when the
free flowing text reaches the end of a
bounding box that is narrower than
the margin box. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . It continues on the
next page as if the previous bounding
box was cloned. If we want it to have
the same border as the one on the
previous page we will need to stroke
the boundaries again.
Span is a different kind of bounding box as it lets the text flow
gracefully onto the next page. It doesn't matter if the text started
on the middle of the previous page, when it flows to the next page
it will start at the beginning. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ I told you it would start
on the beginning of this page.
text/positioned_text.rb
Sometimes we want the text on a specific position on the page. The text method just won't help
us.
There are two other methods for this task: draw_text and text_box.
draw_text is very simple. It will render text starting at the position provided to the :at option. It
won't flow to a new line even if it hits the document boundaries so it is best suited for short text.
text_box gives us much more control over the output. Just provide :width and :height
options and the text will flow accordingly. Even if you don't provide a :width option the text will
flow to a new line if it reaches the right border.
Given that said, text_box is the better option available.
draw_text"Thisdraw_textlineisabsolutepositioned.Howeverdon't"+
"expectittoflowevenifithitsthedocumentborder",
:at=>[200,300]
text_box"Thisisatextbox,youcancontrolwhereitwillflowby"+
"specifyingthe:heightand:widthoptions",
:at=>[100,250],
:height=>100,
:width=>100
text_box"Anothertextboxwithno:widthoptionpassed,soitwill"+
"flowtoanewlinewheneveritreachestherightmargin.",
:at=>[200,100]
This draw_text line is absolute positioned. However don't expect it to flow even if it hits the document border
This is a text box,
you can control
where it will flow
by specifying the
:height and :width
options
Another text box with no :width option passed, so it will flow to a
new line whenever it reaches the right margin.
text/text_box_overflow.rb
The text_box method accepts both :width and :height options. So what happens if the text
doesn't fit the box?
The default behavior is to truncate the text but this can be changed with the :overflow option.
Available modes are :expand (the box will increase to fit the text) and :shrink_to_fit (the text
font size will be shrunk to fit).
If :shrink_to_fit mode is used with the :min_font_size option set. The font size will not be
reduced to less than the value provided even if it means truncating some text.
If the :disable_wrap_by_char is set to true then any text wrapping done while using the
:shrink_to_fit mode will not break up the middle of words.
string="Thisisthesampletextusedforthetextboxes.Seehowit"+
"behavewiththevariousoverflowoptionsused."
textstring
y_position=cursor-20
[:truncate,:expand,:shrink_to_fit].each_with_indexdo|mode,i|
text_boxstring,:at=>[i*150,y_position],
:width=>100,:height=>50,
:overflow=>mode
end
string="Iftheboxistoosmallforthetext,:shrink_to_fit"+
"canrenderthetextinareallysmallfontsize."
move_down120
textstring
y_position=cursor-20
[nil,8,10,12].each_with_indexdo|value,index|
text_boxstring,:at=>[index*150,y_position],
:width=>50,:height=>50,
:overflow=>:shrink_to_fit,
:min_font_size=>value
end
This is the sample text used for the text boxes. See how it behave with the various overflow options
used.
This is the sample
text used for the
text boxes. See
This is the sample
text used for the
text boxes. See
how it behave with
the various
overflow options
used.
This is the sample text
used for the text boxes.
See how it behave with
the various overflow
options used.
If the box is too small for the text, :shrink_to_fit can render the text in a really small font size.
If the box is too
small for the text,
:shrink_to_fit can
render the text in
a really small
font size.
If the box is
too small for
the text,
:shrink_to_fit
can render
If the box
is too
small for
the text,
If the box
is too
small for
text/text_box_excess.rb
Whenever the text_box method truncates text, this truncated bit is not lost, it is the method
return value and we can take advantage of that.
We just need to take some precautions.
This example renders as much of the text as will fit in a larger font inside one text_box and then
proceeds to render the remaining text in the default size in a second text_box.
string="Thisisthebeginningofthetext.Itwillbecutsomewhereand"+
"therestofthetextwillprocedetoberenderedthistimeby"+
"callinganothermethod."+"."*50
y_position=cursor-20
excess_text=text_boxstring,
:width=>300,
:height=>50,
:overflow=>:truncate,
:at=>[100,y_position],
:size=>18
text_boxexcess_text,
:width=>300,
:at=>[100,y_position-100]
This is the beginning of the text. It will
be cut somewhere and the rest of the
text will procede to be rendered this time by calling
another method. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
text/column_box.rb
The column_box method allows you to define columns that flow their contents from one section
to the next. You can have a number of columns on the page, and only when the last column
overflows will a new page be created.
text"ThePrince",:align=>:center,:size=>18
text"NiccolMachiavelli",:align=>:center,:size=>14
move_down12
column_box([0,cursor],:columns=>2,:width=>bounds.width)do
text((<<-END.gsub(/\s+/,'')+"\n\n")*3)
AlltheStatesandGovernmentsbywhichmenareoreverhavebeenruled,
havebeenandareeitherRepublicsorPrincedoms.Princedomsareeither
hereditary,inwhichthesovereigntyisderivedthroughanancientline
ofancestors,ortheyarenew.NewPrincedomsareeitherwhollynew,as
thatofMilantoFrancescoSforza;ortheyarelikelimbsjoinedonto
thehereditarypossessionsofthePrincewhoacquiresthem,asthe
KingdomofNaplestothedominionsoftheKingofSpain.TheStatesthus
acquiredhaveeitherbeenusedtoliveunderaPrinceorhavebeenfree;
andhewhoacquiresthemdoessoeitherbyhisownarmsorbythearmsof
others,andeitherbygoodfortuneorbymerit.
END
end
The Prince
Niccol Machiavelli
All the States and Governments by which men
are or ever have been ruled, have been and are
either Republics or Princedoms. Princedoms are
either hereditary, in which the sovereignty is
derived through an ancient line of ancestors, or
they are new. New Princedoms are either wholly
new, as that of Milan to Francesco Sforza; or they
are like limbs joined on to the hereditary
possessions of the Prince who acquires them, as
the Kingdom of Naples to the dominions of the
King of Spain. The States thus acquired have
either been used to live under a Prince or have
been free; and he who acquires them does so
either by his own arms or by the arms of others,
and either by good fortune or by merit.
All the States and Governments by which men
are or ever have been ruled, have been and are
either Republics or Princedoms. Princedoms are
either hereditary, in which the sovereignty is
derived through an ancient line of ancestors, or
they are new. New Princedoms are either wholly
new, as that of Milan to Francesco Sforza; or they
are like limbs joined on to the hereditary
possessions of the Prince who acquires them, as
the Kingdom of Naples to the dominions of the
King of Spain. The States thus acquired have
either been used to live under a Prince or have
been free; and he who acquires them does so
either by his own arms or by the arms of others,
and either by good fortune or by merit.
All the States and Governments by which men
are or ever have been ruled, have been and are
either Republics or Princedoms. Princedoms are
either hereditary, in which the sovereignty is
derived through an ancient line of ancestors, or
they are new. New Princedoms are either wholly
new, as that of Milan to Francesco Sforza; or they
are like limbs joined on to the hereditary
possessions of the Prince who acquires them, as
the Kingdom of Naples to the dominions of the
King of Spain. The States thus acquired have
either been used to live under a Prince or have
been free; and he who acquires them does so
either by his own arms or by the arms of others,
and either by good fortune or by merit.
text/font.rb
The font method can be used in three different ways.
If we don't pass it any arguments it will return the current font being used to render text.
If we just pass it a font name it will use that font for rendering text through the rest of the document.
It can also be used by passing a font name and a block. In this case the specified font will only be
used to render text inside the block.
The default font is Helvetica.
text"Let'sseewhichfontweareusing:#{font.inspect}"
move_down20
font"Times-Roman"
text"WritteninTimes."
move_down20
font("Courier")do
text"WritteninCourierbecauseweareinsidetheblock."
end
move_down20
text"WritteninTimesagainasweleftthepreviousblock."
move_down20
text"Let'sseewhichfontweareusingagain:#{font.inspect}"
move_down20
font"Helvetica"
text"Backtonormal."
Let's see which font we are using: Prawn::Font::AFM< Helvetica: 12 >
Written in Times.
Written in Courier because we are inside the block.
Written in Times again as we left the previous block.
Let's see which font we are using again: Prawn::Font::AFM< Times-Roman: 12 >
Back to normal.
text/font_size.rb
The font_size method works just like the font method.
In fact we can even use font with the :size option to declare which size we want.
Another way to change the font size is by supplying the :size option to the text methods.
The default font size is 12.
text"Let'sseewhichisthecurrentfont_size:#{font_size.inspect}"
move_down10
font_size16
text"Yeah,somethingbigger!"
move_down10
font_size(25){text"Evenbigger!"}
move_down10
text"Backto16again."
move_down10
text"Singlelineon20usingthe:sizeoption.",:size=>20
move_down10
text"Backto16oncemore."
move_down10
font("Courier",:size=>10)do
text"Yeah,usingCourier10courtesyofthefontmethod."
end
move_down10
font("Helvetica",:size=>12)
text"Backtonormal"
Let's see which is the current font_size: 12
Yeah, something bigger!
Even bigger!
Back to 16 again.
Single line on 20 using the :size option.
Back to 16 once more.
Yeah, using Courier 10 courtesy of the font method.
Back to normal
text/font_style.rb
Most font families come with some styles other than normal. Most common are bold, italic and
bold_italic.
The style can be set the using the :style option, with either the font method which will set the
font and style for rest of the document, or with the inline text methods.
["Courier","Helvetica","Times-Roman"].eachdo|example_font|
move_down20
[:bold,:bold_italic,:italic,:normal].eachdo|style|
fontexample_font,:style=>style
text"I'mwritingin#{example_font}(#{style})"
end
end
I'm writing in Courier (bold)
I'm writing in Courier (bold_italic)
I'm writing in Courier (italic)
I'm writing in Courier (normal)
I'm writing in Helvetica (bold)
I'm writing in Helvetica (bold_italic)
I'm writing in Helvetica (italic)
I'm writing in Helvetica (normal)
I'm writing in Times-Roman (bold)
I'm writing in Times-Roman (bold_italic)
I'm writing in Times-Roman (italic)
I'm writing in Times-Roman (normal)
text/color.rb
The :color attribute can give a block of text a default color, in RGB hex format or 4-value CMYK.
text"Defaultcolorisblack"
move_down25
text"Changedtored",:color=>"FF0000"
move_down25
text"CMYKcolor",:color=>[22,55,79,30]
move_down25
text"Alsoworkswith<colorrgb='ff0000'>inline</color>formatting",
:color=>"0000FF",
:inline_format=>true
Default color is black
Changed to red
CMYK color
Also works with inline formatting
text/alignment.rb
Horizontal text alignment can be achieved by supplying the :align option to the text methods.
Available options are :left (default), :right, :center, and :justify.
Vertical text alignment can be achieved using the :valign option with the text methods. Available
options are :top (default), :center, and :bottom.
Both forms of alignment will be evaluated in the context of the current bounding_box.
text"Thistextshouldbeleftaligned"
text"Thistextshouldbecentered",:align=>:center
text"Thistextshouldberightaligned",:align=>:right
bounding_box([0,220],:width=>250,:height=>220)do
text"Thistextisflowingfromtheleft."*4
move_down15
text"Thistextisflowingfromthecenter."*3,:align=>:center
move_down15
text"Thistextisflowingfromtheright."*4,:align=>:right
move_down15
text"Thistextisjustified."*6,:align=>:justify
transparent(0.5){stroke_bounds}
end
bounding_box([300,220],:width=>250,:height=>220)do
text"Thistextshouldbeverticallytopaligned"
text"Thistextshouldbeverticallycentered",:valign=>:center
text"Thistextshouldbeverticallybottomaligned",:valign=>:bottom
transparent(0.5){stroke_bounds}
end
This text should be left aligned
This text should be centered
This text should be right aligned
This text is flowing from the left. This text is
flowing from the left. This text is flowing from
the left. This text is flowing from the left.
This text is flowing from the center. This text is
flowing from the center. This text is flowing
from the center.
This text is flowing from the right. This text is
flowing from the right. This text is flowing from
the right. This text is flowing from the right.
This text is justified. This text is justified. This
text is justified. This text is justified. This text is
justified. This text is justified.
This text should be vertically top aligned
This text should be vertically centered
This text should be vertically bottom aligned
text/leading.rb
Leading is the additional space between lines of text.
The leading can be set using the default_leading method which applies to the rest of the
document or until it is changed, or inline in the text methods with the :leading option.
The default leading is 0.
string="Hey,whatdidyoudowiththespacebetweenmylines?"*10
textstring,:leading=>0
move_down20
default_leading5
textstring
move_down20
textstring,:leading=>10
Hey, what did you do with the space between my lines? Hey, what did you do with the space between
my lines? Hey, what did you do with the space between my lines? Hey, what did you do with the
space between my lines? Hey, what did you do with the space between my lines? Hey, what did you
do with the space between my lines? Hey, what did you do with the space between my lines? Hey,
what did you do with the space between my lines? Hey, what did you do with the space between my
lines? Hey, what did you do with the space between my lines?
Hey, what did you do with the space between my lines? Hey, what did you do with the space between
my lines? Hey, what did you do with the space between my lines? Hey, what did you do with the
space between my lines? Hey, what did you do with the space between my lines? Hey, what did you
do with the space between my lines? Hey, what did you do with the space between my lines? Hey,
what did you do with the space between my lines? Hey, what did you do with the space between my
lines? Hey, what did you do with the space between my lines?
Hey, what did you do with the space between my lines? Hey, what did you do with the space between
my lines? Hey, what did you do with the space between my lines? Hey, what did you do with the
space between my lines? Hey, what did you do with the space between my lines? Hey, what did you
do with the space between my lines? Hey, what did you do with the space between my lines? Hey,
what did you do with the space between my lines? Hey, what did you do with the space between my
lines? Hey, what did you do with the space between my lines?
text/kerning_and_character_spacing.rb
Kerning is the process of adjusting the spacing between characters in a proportional font. It is
usually done with specific letter pairs. We can switch it on and off if it is available with the current
font. Just pass a boolean value to the :kerning option of the text methods.
Character Spacing is the space between characters. It can be increased or decreased and will
have effect on the whole text. Just pass a number to the :character_spacing option from the
text methods.
font_size(30)do
text_box"Withkerning:",:kerning=>true,:at=>[0,y-40]
text_box"Withoutkerning:",:kerning=>false,:at=>[0,y-80]
text_box"Tomato",:kerning=>true,:at=>[250,y-40]
text_box"Tomato",:kerning=>false,:at=>[250,y-80]
text_box"WAR",:kerning=>true,:at=>[400,y-40]
text_box"WAR",:kerning=>false,:at=>[400,y-80]
text_box"F.",:kerning=>true,:at=>[500,y-40]
text_box"F.",:kerning=>false,:at=>[500,y-80]
end
move_down80
string="Whathaveyoudonetothespacebetweenthecharacters?"
[-2,-1,0,0.5,1,2].eachdo|spacing|
move_down20
text"#{string}(character_spacing:#{spacing})",
:character_spacing=>spacing
end
With kerning:
Without kerning:
Tomato
Tomato
WAR
WAR
F.
F.
What have you done to the space between the characters? (character_spacing: -2)
What have you done to the space between the characters? (character_spacing: -1)
What have you done to the space between the characters? (character_spacing: 0)
What have you done to the space between the characters? (character_spacing: 0.5)
What have you done to the space between the characters? (character_spaci ng: 1)
What have you done t o t he s pac e bet ween t he c har ac t er s ?
( c har ac t er _s pac i ng: 2)
text/paragraph_indentation.rb
Prawn strips all whitespace from the beginning and the end of strings so there are two ways to
indent paragraphs:
One is to use non-breaking spaces which Prawn won't strip. One shortcut to using them is the
Prawn::Text::NBSP.
The other is to use the :indent_paragraphs option with the text methods. Just pass a number
with the space to indent the first line in each paragraph.
#Usingnon-breakingspaces
text""*10+"Thisparagraphwon'tbeindented."*10+
"\n#{Prawn::Text::NBSP*10}"+"ThisonewillwithNBSP."*10
move_down20
text"Thisparagraphwillbeindented."*10+
"\n"+"Thisonewilltoo."*10,
:indent_paragraphs=>60
This paragraph won't be indented. This paragraph won't be indented. This paragraph won't be
indented. This paragraph won't be indented. This paragraph won't be indented. This paragraph won't
be indented. This paragraph won't be indented. This paragraph won't be indented. This paragraph
won't be indented. This paragraph won't be indented.
This one will with NBSP. This one will with NBSP. This one will with NBSP. This one will with
NBSP. This one will with NBSP. This one will with NBSP. This one will with NBSP. This one will with
NBSP. This one will with NBSP. This one will with NBSP.
This paragraph will be indented. This paragraph will be indented. This paragraph will be
indented. This paragraph will be indented. This paragraph will be indented. This paragraph will be
indented. This paragraph will be indented. This paragraph will be indented. This paragraph will be
indented. This paragraph will be indented.
This one will too. This one will too. This one will too. This one will too. This one will too.
This one will too. This one will too. This one will too. This one will too. This one will too.
text/rotation.rb
Rotating text is best avoided on free flowing text, so this example will only use the text_box
method as we can have much more control over its output.
To rotate text all we need to do is use the :rotate option passing an angle in degrees and an
optional :rotate_around to indicate the origin of the rotation (the default is :upper_left).
width=100
height=60
angle=30
x=200
y=cursor-30
stroke_rectangle[0,y],width,height
text_box("Thistextwasnotrotated",
:at=>[0,y],:width=>width,:height=>height)
stroke_rectangle[0,y-100],width,height
text_box("Thistextwasrotatedaroundthecenter",
:at=>[0,y-100],:width=>width,:height=>height,
:rotate=>angle,:rotate_around=>:center)
[:lower_left,:upper_left,
:lower_right,:upper_right].each_with_indexdo|corner,index|
y=y-100ifindex==2
stroke_rectangle[x+(index%2)*200,y],width,height
text_box("Thistextwasrotatedaroundthe#{corner}corner.",
:at=>[x+(index%2)*200,y],
:width=>width,
:height=>height,
:rotate=>angle,
:rotate_around=>corner)
end
This text was not
rotated
T
h
i
s
t
e
x
t
w
a
s
r
o
t
a
t
e
d
a
r
o
u
n
d
t
h
e
c
e
n
t
e
r
T
h
i
s
t
e
x
t
w
a
s
r
o
t
a
t
e
d
a
r
o
u
n
d
t
h
e
l
o
w
e
r
_
l
e
f
t
c
o
r
n
e
r
.
T
h
i
s
t
e
x
t
w
a
s
r
o
t
a
t
e
d
a
r
o
u
n
d
t
h
e
u
p
p
e
r
_
l
e
f
t
c
o
r
n
e
r
.
T
h
i
s
t
e
x
t
w
a
s
r
o
t
a
t
e
d
a
r
o
u
n
d
t
h
e
l
o
w
e
r
_
r
i
g
h
t
c
o
r
n
e
r
.
T
h
i
s
t
e
x
t
w
a
s
r
o
t
a
t
e
d
a
r
o
u
n
d
t
h
e
u
p
p
e
r
_
r
i
g
h
t
c
o
r
n
e
r
.
text/inline.rb
Inline formatting gives you the option to format specific portions of a text. It uses HTML-esque
syntax inside the text string. Supported tags are: b (bold), i (italic), u (underline),
strikethrough, sub (subscript), sup (superscript)
The following tags accept specific attributes: font accepts size, name, and
character_spacing; color accepts rgb and cmyk; link accepts href for external links.
%w[biustrikethroughsubsup].eachdo|tag|
text"Justyourregulartext<#{tag}>exceptthisportion</#{tag}>"+
"isusingthe#{tag}tag",
:inline_format=>true
move_down10
end
text"This<fontsize='18'>line</font>uses"+
"<fontname='Courier'>allthefonttag</font>attributesin"+
"<fontcharacter_spacing='2'>asingleline</font>.",
:inline_format=>true
move_down10
text"Coloringin<colorrgb='FF00FF'>bothRGB</color>"+
"<colorc='100'm='0'y='0'k='0'>andCMYK</color>",
:inline_format=>true
move_down10
text"Thisanexternallinktothe"+
"<u><linkhref='https://github.com/prawnpdf/prawn/wiki'>Prawnwiki"+
"</link></u>",
:inline_format=>true
Just your regular text except this portion is using the b tag
Just your regular text except this portion is using the i tag
Just your regular text except this portion is using the u tag
Just your regular text except this portion is using the strikethrough tag
Just your regular text
except this portion
is using the sub tag
Just your regular text
except this portion
is using the sup tag
This line uses all the font tag attributes in a s i ngl e l i ne.
Coloring in both RGB and CMYK
This an external link to the Prawn wiki
text/formatted_text.rb
There are two other text methods available: formatted_text and formatted_text_box.
These are useful when the provided text has numerous portions that need to be formatted
differently. As you might imply from their names the first should be used for free flowing text just
like the text method and the last should be used for positioned text just like text_box.
The main difference between these methods and the text and text_box methods is how the
text is provided. The formatted_text and formatted_text_box methods accept an array of
hashes. Each hash must provide a :text option which is the text string and may provide the
following options: :styles (an array of symbols), :size (the font size), :character_spacing
(additional space between the characters), :font (the name of a registered font), :color (the
same input accepted by fill_color and stroke_color), :link (an URL to create a link), and
:local (a link to a local file).
formatted_text[{:text=>"Somebold.",:styles=>[:bold]},
{:text=>"Someitalic.",:styles=>[:italic]},
{:text=>"Bolditalic.",:styles=>[:bold,:italic]},
{:text=>"BiggerText.",:size=>20},
{:text=>"Morespacing.",:character_spacing=>3},
{:text=>"DifferentFont.",:font=>"Courier"},
{:text=>"Somecoloring.",:color=>"FF00FF"},
{:text=>"Linktothewiki.",
:color=>"0000FF",
:link=>"https://github.com/prawnpdf/prawn/wiki"},
{:text=>"Linktoalocalfile.",
:color=>"0000FF",
:local=>"./local_file.txt"}
]
formatted_text_box[{:text=>"Justyourregular"},
{:text=>"text_box",:font=>"Courier"},
{:text=>"withsomeadditionalformattingoptions"+
"addedtothemix.",
:color=>[50,100,0,0],
:styles=>[:italic]}
],:at=>[100,100],:width=>200,:height=>100
Some bold. Some italic. Bold italic. Bigger Text. M o r e s p a c i n g . Different Font.
Some coloring. Link to the wiki. Link to a local file.
Just your regular text_box with
some additional formatting options
added to the mix.
text/formatted_callbacks.rb
The :callback option is also available for the formatted text methods.
This option accepts an object (or array of objects) on which two methods will be called if defined:
render_behind and render_in_front. They are called before and after rendering the text
fragment and are passed the fragment as an argument.
This example defines two new callback classes and provide callback objects for the formatted_text
classHighlightCallback
definitialize(options)
@color=options[:color]
@document=options[:document]
end
defrender_behind(fragment)
[email protected]_color
@document.fill_color=@color
@document.fill_rectangle(fragment.top_left,fragment.width,
fragment.height)
@document.fill_color=original_color
end
end
classConnectedBorderCallback
definitialize(options)
@radius=options[:radius]
@document=options[:document]
end
defrender_in_front(fragment)
@document.stroke_polygon(fragment.top_left,fragment.top_right,
fragment.bottom_right,fragment.bottom_left)
@document.fill_circle(fragment.top_left,@radius)
@document.fill_circle(fragment.top_right,@radius)
@document.fill_circle(fragment.bottom_right,@radius)
@document.fill_circle(fragment.bottom_left,@radius)
end
end
highlight=HighlightCallback.new(:color=>'ffff00',:document=>self)
border=ConnectedBorderCallback.new(:radius=>2.5,:document=>self)
formatted_text[{:text=>"hello",:callback=>highlight},
{:text=>""},
{:text=>"world",:callback=>border},
{:text=>""},
{:text=>"helloworld",:callback=>[highlight,border]}
],:size=>20
hello world hello world
text/rendering_and_color.rb
You have already seen how to set the text color using both inline formatting and the format text
methods. There is another way by using the graphics methods fill_color and stroke_color.
When reading the graphics reference you learned about fill and stroke. If you haven't read it before,
read it now before continuing.
Text can be rendered by being filled (the default mode) or just stroked or both filled and stroked.
This can be set using the text_rendering_mode method or the :mode option on the text
methods.
fill_color"00ff00"
stroke_color"0000ff"
font_size(40)do
#normalrenderingmode:fill
text"Thistextisfilledwithgreen."
move_down20
#inlinerenderingmode:stroke
text"Thistextisstrokedwithblue",:mode=>:stroke
move_down20
#blockrenderingmode:fillandstroke
text_rendering_mode(:fill_stroke)do
text"Thistextisfilledwithgreenandstrokedwithblue"
end
end
This text is filled with green.
text/text_box_extensions.rb
We've already seen one way of using text boxes with the text_box method. Turns out this
method is just a convenience for using the Prawn::Text::Box class as it creates a new object
and call render on it.
Knowing that any extensions we add to Prawn::Text::Box will take effect when we use the
text_box method. To add an extension all we need to do is append the
Prawn::Text::Box.extensions array with a module.
moduleTriangleBox
defavailable_width
height+25
end
end
y_position=cursor-10
width=100
height=100
Prawn::Text::Box.extensions<<TriangleBox
stroke_rectangle([0,y_position],width,height)
text_box("A"*100,
:at=>[0,y_position],
:width=>width,
:height=>height)
Prawn::Text::Formatted::Box.extensions<<TriangleBox
stroke_rectangle([200,y_position],width,height)
formatted_text_box([:text=>"A"*100,:color=>"009900"],
:at=>[200,y_position],
:width=>width,
:height=>height)
#Herewecleartheextensionsarray
Prawn::Text::Box.extensions.clear
Prawn::Text::Formatted::Box.extensions.clear
AAA
AAAA
AAAAAA
AAAAAAA
AAAAAAAAA
AAAAAAAAAAA
AAAAAAAAAAAAA
AAA
AAAA
AAAAAA
AAAAAAA
AAAAAAAAA
AAAAAAAAAAA
AAAAAAAAAAAAA
text/single_usage.rb
The PDF format has some built-in font support. If you want to use other fonts in Prawn you need to
embed the font file.
Doing this for a single font is extremely simple. Remember the Styling font example? Another use
of the font method is to provide a font file path and the font will be embedded in the document
and set as the current font.
This is reasonable if a font is used only once, but, if a font used several times, providing the path
each time it is used becomes cumbersome. The example on the next page shows a better way to
deal with fonts which are used several times in a document.
#UsingaTTFfontfile
font("#{Prawn::DATADIR}/fonts/DejaVuSans.ttf")do
text"WrittenwiththeDejaVuSansTTFfont."
end
move_down20
text"Writtenwiththedefaultfont."
move_down20
#UsinganDFONTfontfile
font("#{Prawn::DATADIR}/fonts/Panic+Sans.dfont")do
text"WrittenwiththePanicSansDFONTfont"
end
move_down20
text"Writtenwiththedefaultfontoncemore."
Written with the DejaVu Sans TTF font.
Written with the default font.
Written with the Panic Sans DFONT font
Written with the default font once more.
text/registering_families.rb
Registering font families will help you when you want to use a font over and over or if you would
like to take advantage of the :style option of the text methods and the b and i tags when using
inline formatting.
To register a font family update the font_families hash with the font path for each style you
want to use.
#RegisteringasingleTTFfont
font_families.update("DejaVuSans"=>{
:normal=>"#{Prawn::DATADIR}/fonts/DejaVuSans.ttf"
})
font("DejaVuSans")do
text"UsingtheDejaVuSansfontprovidingonlyitsnametothefontmethod"
end
move_down20
#RegisteringaDFONTpackage
font_path="#{Prawn::DATADIR}/fonts/Panic+Sans.dfont"
font_families.update("PanicSans"=>{
:normal=>{:file=>font_path,:font=>"PanicSans"},
:italic=>{:file=>font_path,:font=>"PanicSans-Italic"},
:bold=>{:file=>font_path,:font=>"PanicSans-Bold"},
:bold_italic=>{:file=>font_path,:font=>"PanicSans-BoldItalic"}
})
font"PanicSans"
text"AlsousingPanicSansbyprovidingonlyitsname"
move_down20
text"Taking<b>advantage</b>ofthe<i>inlineformatting</i>",
:inline_format=>true
move_down20
[:bold,:bold_italic,:italic,:normal].eachdo|style|
text"Usingthe#{style}styleoption.",
:style=>style
move_down10
end
Using the DejaVu Sans font providing only its name to the font method
Also using Panic Sans by providing only its name
Taking advantage of the inline formatting
Using the bold style option.
Using the bold_italic style option.
Using the italic style option.
Using the normal style option.
text/utf8.rb
Multilingualization isn't much of a problem on Prawn as its default encoding is UTF-8. The only
thing you need to worry about is if the font support the glyphs of your language.
text"Takethisexample,asimpleEurosign:"
text"",:size=>32
move_down20
text"Seemsok.Nowlet'strysomethingmorecomplex:"
text"!"#$%&"'()%*+%","-./$0/$$1,(2#3/(-."
move_down20
text"Lookslikethecurrentfont(#{font.inspect})doesn'tsupportthose."
text"Let'strythemwithanotherfont."
move_down20
font("#{Prawn::DATADIR}/fonts/DejaVuSans.ttf")do
text"!"#$%&"'()%*+%","-./$0/$$1,(2#3/(-."
text"Thereyougo."
end
Take this example, a simple Euro sign: