Perl Requires Chilkat v11.7.0+
Chilkat2 Perl
Optimizing a Signed PDF (PreserveSignatures)
See more PDF Optimization Examples
Demonstrates what happens when a signed PDF is optimized. Optimizing rewrites the document, and a rewrite breaks every existing digital signature, so with PreserveSignatures true (the default) Optimize refuses and LastErrorText says why. Setting PreserveSignatures to false allows it, and the signature that was in the file no longer verifies afterwards. "audit" is always allowed, because it changes nothing.Chilkat Perl Downloads
use strict;
use warnings;
use Chilkat2;
# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.
# The PDF used in this example is available at invoice_signed.pdf
my $pdf = Chilkat2::Pdf->new;
my $success = $pdf->LoadFile('qa_data/pdf/invoice_signed.pdf');
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
print 'signatures: ', $pdf->NumSignatures, "\n";
my $json = Chilkat2::JsonObject->new;
my $jsonOut = Chilkat2::JsonObject->new;
# An audit changes nothing, so it is allowed on a signed PDF.
$success = $pdf->Optimize('audit', $json, $jsonOut);
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
print 'audit ok, estimated savings: ', $jsonOut->IntOf('estimatedSavings.total'), "\n";
# Optimizing is refused while PreserveSignatures is true.
$success = $pdf->Optimize('optimize', $json, $jsonOut);
if (!$success) {
print "Refused while PreserveSignatures is true.\n";
}
# Allow the rewrite. Do this only when the signatures no longer matter -- an invoice being
# archived, say, where the signed original is kept elsewhere.
$pdf->PreserveSignatures(0);
$success = $pdf->Optimize('optimize', $json, $jsonOut);
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
$success = $pdf->WriteFile('qa_output/invoice_optimized.pdf');
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
print 'optimized, bytesSaved: ', $jsonOut->IntOf('bytesSaved'), "\n";
# The signature is still in the file, but it no longer verifies: the bytes it covered have changed.
my $pdf2 = Chilkat2::Pdf->new;
$success = $pdf2->LoadFile('qa_output/invoice_optimized.pdf');
if (!$success) {
print $pdf2->LastErrorText, "\n";
exit;
}
print 'signatures after: ', $pdf2->NumSignatures, "\n";
my $sigInfo = Chilkat2::JsonObject->new;
my $verified = $pdf2->VerifySignature(0, $sigInfo);
print 'verifies after optimizing: ', ($verified ? 1 : 0), "\n";