Perl Requires Chilkat v11.7.0+
Chilkat2 Perl
Password-Protect a PDF with AES-256 Encryption
See more PDF Protection Examples
Demonstrates the simplest way to encrypt a PDF so that it needs a password to open. The passwords come from the UserPassword and OwnerPassword properties, and Protection with the encrypt operation and an empty JSON uses the defaults: AES-256, everything encrypted, every permission granted. Protection only records the security the PDF will be saved with. Nothing is encrypted until WriteFile is called.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 two_page_memo.pdf
my $pdf = Chilkat2::Pdf->new;
my $success = $pdf->LoadFile('qa_data/pdf/two_page_memo.pdf');
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
# The passwords are taken from these two properties at the time Protection is called.
# The user password opens the PDF. The owner password opens it too, and is the one needed
# later to change or remove the protection.
$pdf->UserPassword('user-secret');
$pdf->OwnerPassword('owner-secret');
# An empty JSON asks for the defaults: AES-256, everything encrypted, every permission granted.
my $json = Chilkat2::JsonObject->new;
my $jsonOut = Chilkat2::JsonObject->new;
$success = $pdf->Protection('encrypt', $json, $jsonOut);
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
# Nothing has been encrypted yet. "pending" describes the security the PDF will be saved with.
print 'algorithm: ', $jsonOut->StringOf('pending.algorithm'), "\n";
print 'PDF version: ', $jsonOut->StringOf('pending.pdfVersion'), "\n";
print 'password needed to open: ', ($jsonOut->BoolOf('pending.userPasswordRequired') ? 1 : 0), "\n";
# Writing the file applies it.
$success = $pdf->WriteFile('qa_output/memo_encrypted.pdf');
if (!$success) {
print $pdf->LastErrorText, "\n";
exit;
}
# PreLoadCheck reports a file's encryption without loading it, and needs no password.
my $checker = Chilkat2::Pdf->new;
my $info = Chilkat2::JsonObject->new;
$success = $checker->PreLoadCheck('qa_output/memo_encrypted.pdf', $info);
if (!$success) {
print $checker->LastErrorText, "\n";
exit;
}
print 'encrypted: ', ($info->BoolOf('encrypted') ? 1 : 0), "\n";
print 'openPasswordRequired: ', ($info->BoolOf('openPasswordRequired') ? 1 : 0), "\n";
# With the password, the PDF opens normally.
my $reader = Chilkat2::Pdf->new;
$reader->UserPassword('user-secret');
$success = $reader->LoadFile('qa_output/memo_encrypted.pdf');
if (!$success) {
print $reader->LastErrorText, "\n";
exit;
}
print 'pages: ', $reader->NumPages, "\n";
# Sample output:
# algorithm: aes-256
# PDF version: 1.7
# password needed to open: True
# encrypted: True
# openPasswordRequired: True
# pages: 2