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.
Alternatively, you can use this website to watermark pdf files online.
http://pdfaid.com/watermark.aspx
working nice. Thank you so much
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.
Rick,
I’m sorry, I’ve no idea what’s wrong. My only guess is that maybe you don’t have the font installed that it’s trying to use.
I needed to do all sheets so I used my $count = $pdf->pages(); and a foreach loop. Fabulous! Thank you so much.