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;

$page->mediabox('A4');

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

$eg_trans->transparency(0.7);
$eg_norm->transparency(0);

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

# …

# Save
$pdf->saveas($ofile);
$pdf->end;

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/FontFile.pm line 424.

    Any idea how to solve this.
    Thanks in advance.

Leave a Reply to prasad Cancel reply

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