NAME

PDF::API2::Content - Methods for adding graphics and text to a PDF

SYNOPSIS

# Start with a PDF page (new or opened)
my $pdf = PDF::API2->new();
my $page = $pdf->page();

# Add a new content object
my $content = $page->graphics();
my $content = $page->text();

# Then call the methods below to add graphics and text to the page.

COORDINATE TRANSFORMATIONS

The methods in this section change the coordinate system for the current content object relative to the rest of the document.

Changes to the coordinate system only affect subsequent paths or text.

A call to any of the methods in this section resets the coordinate system before applying its changes, unless the relative option is set.

translate

$content = $content->translate($x, $y);

Moves the origin along the x and y axes.

rotate

$content = $content->rotate($degrees);

Rotates the coordinate system counter-clockwise.

Use a negative argument to rotate clockwise.

scale

$content = $content->scale($x, $y);

Scales (stretches) the coordinate systems along the x and y axes. A value of 1 for either $x or $y represents 100% scale (i.e. no change).

skew

$content = $content->skew($a, $b);

Skews the coordinate system by $a degrees (counter-clockwise) from the x axis and $b degrees (clockwise) from the y axis.

transform

$content = $content->transform(
    translate => [$x, $y],
    rotate    => $degrees,
    scale     => [$x, $y],
    skew      => [$a, $b],
    repeat    => $boolean,
);

Performs multiple coordinate transformations, in the order recommended by the PDF specification (translate, rotate, scale, then skew). Omitted options will be unchanged.

If repeat is true and if this is not the first call to a transformation method, the previous transformation will be performed again, modified by any other provided arguments.

matrix

$graphics = $graphics->matrix($a, $b, $c, $d, $e, $f);

($a, $b, $c, $d, $e, $f) = $text->matrix($a, $b, $c, $d, $e, $f);

Sets the current transformation matrix manually. Unless you have a particular need to enter transformations manually, you should use the transform method instead.

The return value differs based on whether the caller is a graphics content object or a text content object.

GRAPHICS STATE

save

$content = $content->save();

Saves the current graphics state on a stack.

restore

$content = $content->restore();

Restores the most recently saved graphics state, removing it from the stack.

line_width

$content = $content->line_width($points);

Sets the width of the stroke in points.

line_cap

$content = $content->line_cap($style);

Sets the shape that will be used at the ends of open subpaths (and dashes, if any) when they are stroked.

  • "butt" or 0 = Butt Cap, default

    The stroke ends at the end of the path, with no projection.

  • "round" or 1 = Round Cap)

    An arc is drawn around the end of the path with a diameter equal to the line width, and is filled in.

  • "square" or 2 = Projecting Square Cap

    The stroke continues past the end of the path for half the line width.

line_join

$content = $content->line_join($style);

Sets the style of join to be used at corners of a path.

  • "miter" or 0 = Miter Join, default

    The outer edges of the stroke extend until they meet, up to the limit specified below. If the limit would be surpassed, a bevel join is used instead.

  • "round" or 1 = Round Join

    A circle with a diameter equal to the linewidth is drawn around the corner point, producing a rounded corner.

  • "bevel" or 2 = Bevel Join

    A triangle is drawn to fill in the notch between the two strokes.

miter_limit

$content = $content->miter_limit($ratio);

Sets the miter limit when the line join style is a miter join.

The $ratio is the maximum length of the miter (inner to outer corner) divided by the line width. Any miter above this ratio will be converted to a bevel join. The practical effect is that lines meeting at shallow angles are chopped off instead of producing long pointed corners.

There is no documented default miter limit.

line_dash_pattern

# Solid line
$content = $content->line_dash_pattern();

# Equal length lines and gaps
$content = $content->line_dash_pattern($length);

# Specified line and gap lengths
$content = $content->line_dash_pattern($line1, $gap1, $line2, $gap2, ...);

# Offset the starting point
$content = $content->line_dash_pattern(
    pattern => [$line1, $gap1, $line2, $gap2, ...],
    offset => $points,
);

Sets the line dash pattern.

If called without any arguments, a solid line will be drawn.

If called with one argument, the dashes and gaps will have equal lengths.

If called with two or more arguments, the arguments represent alternating dash and gap lengths.

If called with a hash of arguments, a dash phase may be set, which specifies the distance into the pattern at which to start the dash.

flatness_tolerance

$content = $content->flatness_tolerance($tolerance);

Sets the maximum distance in device pixels between the mathematically correct path for a curve and an approximation constructed from straight line segments.

$tolerance is an integer between 0 and 100, where 0 represents the device's default flatness tolerance.

egstate

$content = $content->egstate($object);

Adds a PDF::API2::Resource::ExtGState object containing a set of graphics state parameters.

PATH CONSTRUCTION (DRAWING)

Note that paths will not appear until a path painting method is called ("stroke", "fill", or "paint").

move

$content = $content->move($x, $y);

Starts a new path at the specified coordinates.

line

$content = $content->line($x, $y);

Extends the path in a line from the current coordinates to the specified coordinates.

hline

$content = $content->hline($x);

Extends the path in a horizontal line from the current position to the specified x coordinate.

vline

$content = $content->vline($x);

Extends the path in a vertical line from the current position to the specified y coordinate.

polyline

$content = $content->polyline($x1, $y1, $x2, $y2, ...);

Extends the path from the current position in one or more straight lines.

curve

$content = $content->curve($cx1, $cy1, $cx2, $cy2, $x, $y);

Extends the path in a curve from the current point to ($x, $y), using the two specified points to create a cubic Bezier curve.

spline

$content = $content->spline($cx1, $cy1, $x, $y);

Extends the path in a curve from the current point to ($x, $y), using the two specified points to create a spline.

arc

$content = $content->arc($x, $y, $major, $minor, $a, $b);

Extends the path along an arc of an ellipse centered at [$x, $y]. $major and $minor represent the axes of the ellipse, and the arc moves from $a degrees to $b degrees.

close

$content = $content->close();

Closes the current path by extending a line from the current position to the starting position.

end

$content = $content->end();

Ends the current path without filling or stroking.

SHAPE CONSTRUCTION (DRAWING)

The following are convenience methods for drawing closed paths.

Note that shapes will not appear until a path painting method is called ("stroke", "fill", or "paint").

rectangle

$content = $content->rectangle($x1, $y1, $x2, $y2);

Creates a new rectangle-shaped path, between the two points [$x1, $y1] and [$x2, $y2].

circle

$content = $content->circle($x, $y, $radius);

Creates a new circular path centered on [$x, $y] with the specified radius.

ellipse

$content = $content->ellipse($x, $y, $major, $minor);

Creates a new elliptical path centered on [$x, $y] with the specified major and minor axes.

pie

$content = $content->pie($x, $y, $major, $minor, $a, $b);

Creates a new wedge-shaped path from an ellipse centered on [$x, $y] with the specified major and minor axes, extending from $a degrees to $b degrees.

PATH PAINTING (DRAWING)

stroke_color

$content = $content->stroke_color($color, @arguments);

Sets the stroke color, which is black by default.

# Use a named color
$content->stroke_color('blue');

# Use an RGB color (start with '#')
$content->stroke_color('#FF0000');

# Use a CMYK color (start with '%')
$content->stroke_color('%FF000000');

# Use a spot color with 100% coverage.
my $spot = $pdf->colorspace('spot', 'PANTONE Red 032 C', '#EF3340');
$content->stroke_color($spot, 1.0);

RGB and CMYK colors can have one-byte, two-byte, three-byte, or four-byte values for each color, depending on the level of precision needed. For instance, cyan can be given as %F000 or %FFFF000000000000.

fill_color

$content = $content->fill_color($color, @arguments);

Sets the fill color, which is black by default. Arguments are the same as in "stroke_color".

stroke

$content = $content->stroke();

Strokes the current path.

fill

$content = $content->fill(rule => $rule);

Fills the current path.

$rule describes which areas are filled in when the path intersects with itself.

  • nonzero (default)

    Use the nonzero winding number rule. This tends to mean that the entire area enclosed by the path is filled in, with some exceptions depending on the direction of the path.

  • even-odd

    Use the even-odd rule. This tends to mean that the presence of fill alternates each time the path is intersected.

See PDF specification 1.7 section 8.5.3.3, Filling, for more details.

paint

$content = $content->paint(rule => $rule);

Fills and strokes the current path. $rule is as described in "fill".

clip

$content = $content->clip(rule => $rule);

Modifies the current clipping path (initially the entire page) by intersecting it with the current path following the next path-painting command. $rule is as described in "fill".

EXTERNAL OBJECTS

object

$content = $content->object($object, $x, $y, $scale_x, $scale_y);

Places an image or other external object (a.k.a. XObject) on the page in the specified location.

If $x and $y are omitted, the object will be placed at [0, 0].

For images, $scale_x and $scale_y represent the width and height of the image on the page in points. If $scale_x is omitted, it will default to 72 pixels per inch. If $scale_y is omitted, the image will be scaled proportionally based on the image dimensions.

For other external objects, the scale is a multiplier, where 1 (the default) represents 100% (i.e. no change).

If coordinate transformations have been made (see Coordinate Transformations above), the position and scale will be relative to the updated coordinates.

If no coordinate transformations are needed, this method can be called directly from the PDF::API2::Page object instead.

TEXT STATE

All of the following parameters that take a size are applied before any scaling takes place, so you don't need to adjust values to counteract scaling.

font

$content = $content->font($font, $size);

Sets the font and font size. $font is an object created by calling "font" in PDF::API2 to add the font to the document.

my $pdf = PDF::API2->new();
my $page = $pdf->page();
my $text = $page->text();

my $font = $pdf->font('Helvetica');
$text->font($font, 24);
$text->position(72, 720);
$text->text('Hello, World!');

$pdf->save('sample.pdf');

character_spacing

$spacing = $content->character_spacing($spacing);

Sets the spacing between characters. This is initially zero.

word_spacing

$spacing = $content->word_spacing($spacing);

Sets the spacing between words. This is initially zero (i.e. just the width of the space).

Word spacing might only affect simple fonts and composite fonts where the space character is a single-byte code. This is a limitation of the PDF specification at least as of version 1.7 (see section 9.3.3). It's possible that a later version of the specification will support word spacing in fonts that use multi-byte codes.

hscale

$scale = $content->hscale($scale);

Sets/gets the percentage of horizontal text scaling. Enter a scale greater than 100 to stretch text, less than 100 to squeeze text, or 100 to disable any existing scaling.

leading

$leading = $content->leading($leading);

Sets/gets the text leading, which is the distance between baselines. This is initially zero (i.e. the lines will be printed on top of each other).

render

$mode = $content->render($mode);

Sets the text rendering mode.

  • 0 = Fill text

  • 1 = Stroke text (outline)

  • 2 = Fill, then stroke text

  • 3 = Neither fill nor stroke text (invisible)

  • 4 = Fill text and add to path for clipping

  • 5 = Stroke text and add to path for clipping

  • 6 = Fill, then stroke text and add to path for clipping

  • 7 = Add text to path for clipping

rise

$distance = $content->rise($distance);

Adjusts the baseline up or down from its current location. This is initially zero.

Use this to create superscripts or subscripts (usually with an adjustment to the font size as well).

TEXT PLACEMENT

position

# Set
$content = $content->position($x, $y);

# Get
($x, $y) = $content->position();

If called with arguments, moves to the start of the current line of text, offset by $x and $y.

If called without arguments, returns the current position of the cursor (before the effects of any coordinate transformation methods).

crlf

$content = $content->crlf();

Moves to the start of the next line, based on the "leading" setting.

If leading isn't set, a default distance of 120% of the font size will be used.

text

my $width = $content->text($text, %options);

Places text on the page. Returns the width of the text in points.

Options:

  • align

    One of left (default), center, or right. Text will be placed such that it begins, is centered on, or ends at the current text position, respectively.

    In each case, the position will then be moved to the end of the text.

  • indent

    Indents the text by the number of points.

    If align is set to anything other than left, this setting will be ignored.

  • underline

    Underlines the text. The value may be one of the following:

    • auto

      Determines the underline distance from the text based on the font and font size.

    • $distance

      Manually set the underline distance in points. A positive distance moves the line downward.

    • [$distance, $thickness, ...]

      Manually set both the underline distance and line thickness, both in points.

      Repeat these arguments to include multiple underlines.

text_justified

my $width = $content->text_justified($text, $width, %options);

As text, filling the specified width by adjusting the space between words.

paragraph

# Scalar context
$overflow_text = $content->paragraph($text, $width, $height, %options);

# Array context
($overflow, $height) = $content->paragraph($text, $width, $height, %options);

Fills the rectangle with as much of the provided text as will fit.

In array context, returns the remaining text (if any) of the positioned text and the remaining (unused) height. In scalar context, returns the remaining text (if any).

Line spacing follows "leading", if set, or 120% of the font size by default.

Options

  • align

    Specifies the alignment for each line of text. May be set to left (default), center, right, or justified.

  • align-last

    Specifies the alignment for the last line of justified text. May be set to left (default), center, right, or justified.

  • underline

    As described in "text".

text_width

my $width = $content->text_width($line, %overrides);

Returns the width of a line of text based on the current text state attributes. These can optionally be overridden:

my $width = $content->text_width($line,
    font => $font,
    size => $size,
    character_spacing => $spacing,
    word_spacing => $spacing,
    hscale => $scale,
);

MIGRATION

See "MIGRATION" in PDF::API2 for an overview.

transform(%hyphen_prefixed_options);

Remove hyphens from option names (-translate becomes translate, etc.).

transform_rel

Replace with "transform", setting option repeat to true. Remove hyphens from the names of other options.

linewidth

Replace with "line_width".

linecap

Replace with "line_cap".

linejoin

Replace with "line_join".

meterlimit
miterlimit

Replace with "miter_limit".

linedash

Replace with "line_dash_pattern". Remove hyphens from option names. Rename -shift to offset.

flatness

Replace with "flatness_tolerance".

poly

Replace with "move" (first two arguments) and "polyline" (remaining arguments).

endpath

Replace with "end".

rect

Replace with "rectangle", converting the $w (third) and $h (fourth) arguments to the X and Y values of the upper-right corner:

# Old
$content->rect($x, $y, $w, $h);

# New
$content->rectangle($x, $y, $x + $w, $y + $h);
rectxy

Replace with "rectangle".

fill(1)

Replace with $content->fill(rule => 'even-odd').

fillstroke

Replace with "paint".

clip(1)

Replace with $content->clip(rule => 'even-odd').

image
formimage

Replace with "object".

charspace

Replace with "character_spacing".

wordspace

Replace with "word_spacing".

hspace

Replace with "hscale".

lead

Replace with "leading".

distance

Replace with "position".

cr

Replace with either "position" (if called with arguments) or "crlf" (if called without arguments).

nl

Replace with "crlf".

text(%hyphen_prefixed_options)

Remove initial hyphens from option names.

text_center

Replace with "text", setting align to center.

text_right

Replace with "text", setting align to right.

paragraph(%hyphen_prefixed_options)

Remove initial hyphens from option names. -align-last becomes align-last.

section
paragraphs

Replace with "paragraph".

advancewidth

Replace with "text_width".