1

I am trying to do what I thought was a simple search and replace of tokens in a pdf file.

I have this pdf file: http://servera.service.com/LABELS.pdf

I am using this simple perl script with CAM::PDF to get the page content and do a simple search and replace on tokens.

$pdf = CAM::PDF->new('LABELS.pdf');

$page = $pdf->getPageContent(1);

$page =~ s/\\045\\045Carrier_Tracking_Number\\045\\045/ABE1234567890/;

$pdf->setPageContent(1, $page);

$pdf->cleanoutput('after.pdf');

exit;

What I get is http://servera.service.com/after.pdf

When I dump the page content this is what I have before the substitution

http://servera.service.com/before.txt

and this is what I have after the substitution

http://servera.service.com/after.txt

Obviously I am missing something very simple.

1 Answer 1

0

In my opinion, you didn't do anything wrong, and the code runs as expected as well. But, I didn't say that these numbers '1234567890', which you forced to write into the document, will show exactly as what they look like on PDF.

It is the same reason with the character '%', you replace it with '\045' instead of normally '%'. PDF documents are encoded in CMap (an Adobe build-in encoding table). If you replace the string with '\115', you will get an 'M', '\116' is 'N', '\117' is 'O', but I don't know what '\118' or 'P' is.

'getPageContent' returns the whole layout contents of a page. I suggest you using 'getPageText' instead of 'getPageContent' to get a true string. Then you can replace or handle the string normally.

my $textpage = $pdf->getPageText(1);
$textpage =~ s/%%Carrier_Tracking_Number%%/ABD1234567890/;

Remember, once taken out as a string, you will never put it back in former document format.

P.S. In the module CAM::PDF, the author also provided two string change scripts: changepdfstring.pl and changepagestring.pl. changepdfstring.pl changes the meta data, changepagestring.pl just exactly does what you did. You can refer to them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.