Tuesday, August 31, 2010

The State of the PDF::API2 Graphics Object

Often when I write scripts with PDF::API2, I modify the state of my graphics object a lot. Sometimes to change the current fill color, or line thickness, or perhaps to set line dashing. Usually, once I have finished drawing the object, I want to set the state back to what it was before, and then continue on with the rest of the script. Rather than having to either re-set everything on the graphics object or use a new graphics object, there are two methods that will help you out.

The save and restore methods will, surprisingly, save and restore the state of your graphics object. What makes it even more handy, is that you can save multiple states and have a stack of states. Some example code:

#!/usr/bin/env perl

use warnings;
use strict;

use PDF::API2;

my $pdf = new PDF::API2;

my $page = $pdf->page;
$page->mediabox( 100, 60 );
my $gfx = $page->gfx;

# Make it red.
# Save the first state

$gfx->move( 10, 10 );
$gfx->line( 90, 10 );

# Make it blue, a bit thicker and add some dashing.
$gfx->linedash( 1, 5 );
$gfx->move( 10, 20 );
$gfx->line( 90, 20 );
# Save the second state

# Set some new parameters.
$gfx->move( 10, 30 );
$gfx->line( 90, 30 );

# Revert back to the 'blue' state.
$gfx->move( 10, 40 );
$gfx->line( 90, 40 );

# Revert back to the 'red' state.
$gfx->move( 10, 50 );
$gfx->line( 90, 50 );


Run the code and you should get the following:

Handy, I think.

No comments:

Post a Comment