Encrypted Documents Handle and Create Encrypted PDF Documents

Introduction

The SetaPDF-Merger component is able to process and create PDF documents with standard PDF security throughout because it is based on the Core component

Merging Encrypted Documents

As the security handler of a document needs a kind of authorization to allow the extraction of pages it is a requirement that its document instance is accessable outside of the merger.

This is possible by creating a document instance manually and passing it later to the addDocument() method or by using the getDocumentByFilename() helper method of the Merger class: 

PHP
/* Get the document instance through the Merger. 
 * The document will already be cached in the merger instance
 */
$filename = 'path/to/Example-PDF-1-encrypted.pdf';
$encryptedDoc = $merger->getDocumentByFilename($filename);
$secHandler = $encryptedDoc->getSecHandlerIn();
if ($secHandler instanceof SetaPDF_Core_SecHandler_Standard) {
    // authenticate with a password (in that case the owner password)
    $secHandler->authByOwnerPassword('setapdf');
}

// Add the filename
$merger->addFile($filename);

/* Create a separate document instance 
 */
$filename = 'path/to/Example-PDF-2-encrypted.pdf';
$encryptedDoc = SetaPDF_Core_Document::loadByFilename($filename);
$secHandler = $encryptedDoc->getSecHandlerIn();
if ($secHandler instanceof SetaPDF_Core_SecHandler_Standard) {
    // authenticate with a password (in that case the owner password)
    $secHandler->authByOwnerPassword('setasign');
}

// Add the document instance
$merger->addDocument($encryptedDoc);

Encrypting the Resulting Document

To encrypt the resulting document a security handler has to be passed to the resulting document instance before calling its save() method. Details about creating security handlers can be found here.

PHP
<?php
require_once('library/SetaPDF/Autoload.php');

$merger = new \SetaPDF_Merger();
// add files from the file system
$merger->addFile('files/pdfs/camtown/products/Boombastic-Box.pdf');
$merger->addFile('files/pdfs/camtown/products/Fantastic-Speaker.pdf');
$merger->addFile('files/pdfs/camtown/products/Noisy-Tube.pdf');

// merge them together
$merger->merge();

// get the resulting document instance
$document = $merger->getDocument();

/* define a handler with an owner password and without a user
 * password, allow print and copy, and do not encrypt metadata
 */
$secHandler = \SetaPDF_Core_SecHandler_Standard_Aes128::factory(
    $document,
    'the-owner-password',
    '',
    \SetaPDF_Core_SecHandler::PERM_PRINT | \SetaPDF_Core_SecHandler::PERM_COPY,
    false
);

// Attach the handler to the document
$document->setSecHandler($secHandler);

// add a writer
$document->setWriter(new \SetaPDF_Core_Writer_Http('encrypted.pdf', true));
// save and finish
$document->save()->finish();