Adding watermarks to a PDF with Perl’s PDF::API2

For ages I’ve been trying to work out how to programmatically add a watermark to an existing PDF using the Perl PDF::API2 module.

In case it’s useful for anyone else, here goes:

use warnings;
use strict;

use PDF::API2;

my $ifile = "/some/file.pdf";
my $ofile = "/some/newfile.pdf";
my $pdf   = PDF::API2->open($ifile);
my $fnt   = $pdf->ttfont('verdana.ttf', -encode => 'utf8');
# Only on the front page
my $page  = $pdf->openpage(1);
my $text  = $page->text;


# Create two extended graphic states; one for transparent content
# and one for normal content
my $eg_trans = $pdf->egstate();
my $eg_norm  = $pdf->egstate();


# Go transparent
# Black edges
# With light green fill
# Text render mode: fill text first then put the edges on top
# Diagonal transparent text
$text->textlabel(55, 235, $fnt, 56, "i'm in ur pdf", -rotate => 30);
# Back to non-transparent to do other stuff

# …

# Save

I think there may be better ways of doing this within Perl now, but I already had some code using PDF::API2.

5 thoughts on “Adding watermarks to a PDF with Perl’s PDF::API2

  1. The code looks fie and simply to use. However i have a error while running it:

    cannot find font ” … at /usr/local/lib/perl5/site_perl/5.10.0/PDF/API2/Resource/CIDFont/TrueType/ line 424.

    Any idea how to solve this.
    Thanks in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *