Skip to content

PDF Encrypt

PdfEncrypt applies or removes PDF encryption. It performs a full document rewrite (not incremental), rebuilding the page tree with the new encryption settings.

use Phpdftk\Pdf\Toolkit\PdfEncrypt;
// Unencrypted PDF
$enc = PdfEncrypt::open('doc.pdf');
// Already encrypted -- supply the password to open
$enc = PdfEncrypt::open('encrypted.pdf', password: 'secret');
// From string
$enc = PdfEncrypt::openString($pdfBytes);
use Phpdftk\Pdf\Toolkit\Encryption\EncryptionMethod;
$enc->encrypt('userpass', 'ownerpass', EncryptionMethod::Aes256)
->save('encrypted.pdf');
Enum caseAlgorithm
EncryptionMethod::Rc440RC4 40-bit
EncryptionMethod::Rc4128RC4 128-bit
EncryptionMethod::Aes128AES 128-bit
EncryptionMethod::Aes256AES 256-bit (default)

The default when no method is specified is Aes256.

Remove all encryption, producing an unprotected document:

PdfEncrypt::open('encrypted.pdf', password: 'secret')
->decrypt()
->save('decrypted.pdf');
PdfEncrypt::open('encrypted.pdf', password: 'oldpass')
->changePasswords('newuser', 'newowner')
->save('rekeyed.pdf');

If no encryption method has been explicitly set, changePasswords defaults to AES-256.

Use the Permission constants to control what operations are allowed:

use Phpdftk\Pdf\Toolkit\Encryption\Permission;
$enc->encrypt('user', 'owner', EncryptionMethod::Aes256,
Permission::PRINT | Permission::COPY
);
ConstantDescription
Permission::PRINTPrint the document
Permission::MODIFYModify document contents
Permission::COPYCopy or extract text/graphics
Permission::ANNOTATEAdd or modify annotations
Permission::FILL_FORMSFill in form fields
Permission::ACCESSIBILITYExtract text for accessibility
Permission::ASSEMBLEAssemble the document (insert, rotate, delete pages)
Permission::PRINT_HIGHHigh-resolution printing
Permission::ALLAll permissions granted

Permissions can also be set separately:

$enc->setPermissions(Permission::PRINT | Permission::FILL_FORMS);
$enc->isEncrypted(); // bool
// To file
$enc->save('output.pdf');
// To string
$bytes = $enc->toBytes();
$enc->getPageCount(); // int
$reader = $enc->getReader(); // PdfReader