Perl Requires Chilkat v11.7.0+
Chilkat2 Perl
Optimizing an Encrypted PDF
See more PDF Optimization Examples
Demonstrates optimizing a PDF that is encrypted. Set the password before loading, exactly as for any other operation; the optimized PDF keeps the security it had, so the output still needs the same password. Because Chilkat honours the permissions recorded in the document, optimizing requires owner rights or the "modify" permission: a PDF opened with a user password that forbids modification can be audited but not optimized.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 encrypted_user_password.pdf
my $pdf = Chilkat2::Pdf->new;
# The password must be set before loading.
$pdf->UserPassword('secret');
my $success = $pdf->LoadFile('qa_data/pdf/encrypted_user_password.pdf');
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
# What security does the file have, and may it be modified?
my $json = Chilkat2::JsonObject->new;
my $jsonOut = Chilkat2::JsonObject->new;
$success = $pdf->Protection('getInfo', $json, $jsonOut);
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
print 'encrypted: ', ($jsonOut->BoolOf('loaded.encrypted') ? 1 : 0), "\n";
print 'method: ', $jsonOut->StringOf('loaded.method'), "\n";
print 'openedWith: ', $jsonOut->StringOf('loaded.openedWith'), "\n";
print 'may modify: ', ($jsonOut->BoolOf('loaded.permissions.modify') ? 1 : 0), "\n";
$success = $pdf->Optimize('optimize', $json, $jsonOut);
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
$success = $pdf->WriteFile('qa_output/encrypted_optimized.pdf');
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
print 'bytesSaved: ', $jsonOut->IntOf('bytesSaved'), "\n";
# The output is still encrypted with the same security: loading it without the password fails.
my $noPassword = Chilkat2::Pdf->new;
$success = $noPassword->LoadFile('qa_output/encrypted_optimized.pdf');
my $q = Chilkat2::JsonObject->new;
my $qOut = Chilkat2::JsonObject->new;
$success = $noPassword->ExtractText('assess', $q, $qOut);
print 'passwordRequired without the password: ', ($qOut->BoolOf('quality.passwordRequired') ? 1 : 0), "\n";
# With the password it reads normally.
my $withPassword = Chilkat2::Pdf->new;
$withPassword->UserPassword('secret');
$success = $withPassword->LoadFile('qa_output/encrypted_optimized.pdf');
if (!$success) {
print $withPassword->LastErrorText, "\n";
exit;
}
print 'pages: ', $withPassword->NumPages, "\n";