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.
$gfx->strokecolor('red');
# Save the first state
$gfx->save;

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

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

# Set some new parameters.
$gfx->strokecolor('yellow');
$gfx->linedash();
$gfx->linewidth(3);
$gfx->move( 10, 30 );
$gfx->line( 90, 30 );
$gfx->stroke;

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

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

$pdf->saveas("$0.pdf");

Run the code and you should get the following:

Handy, I think.