Learn how to protect your PDF documents created with TCPDF by setting a password in PHP.

A PDF is the most closest thing to a official document in the digital world, and in the same way in the real life some PDFs are intended to be confidential. And if you want to protect a generated PDF with TCPDF, there’s support for password protected and encryption built in the library and you only need to learn how to use it.

Basically, all you need to do to protect your document is to use the $yourPDF->SetProtection($arguments) method.

Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts. You can extend the execution time increasing the time limit using set_time_limit($seconds) or changing the value in the php.ini file.

About the SetProtection method

The SetProtection method expects up to 5 parameters:

1. Array of permissions

The first parameter is meant to be an array of strings with identifiers as content that indicates which permissions should be removed from the PDF.

  • print : disable the possibility to print the PDF from any PDF viewer.
  • modify : prevent the modification of contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';
  • copy : prevent the copy or otherwise extract text and graphics from the document;
  • annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);
  • fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;
  • extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);
  • assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;
  • print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.
  • owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.

The following code should prevent a PDF from being printed or modified:

$pdf->SetProtection(array('print','modify'));

2. User password

The second parameter is meant to be the password that every user should provide everytime he tries to open the PDF in any PDF viewer. Use null or '' as value to don't use any password for the user.

Password protected PDF in PDF Viewer

The previous image shows a PDF with password trying to be viewed in the Chrome PDF Viewer.

3. Owner password

The master (owner) password, if different from the user one, can be used to get full document access in case you want to revocate any of the removed permissions in any PDF viewer.

4. Encryption type

The encryption type possible values are:

  • 0 = RSA 40 bit
  • 1 = RSA 128 bit
  • 2 = AES 128 bit
  • 3 = AES 256 bit

PDF encryption internally works with encryption keys of 40, 128, or 256 bit depending on the PDF version. The binary encryption key is derived from a password provided by the user.

A encrypted PDF with RSA 40 bit should be created with:

$pdf->SetProtection($permissions,"PasswordForUsers","MyMasterPassword",0);

5. Sign pdf with public key

In case you want to sign the PDF with a public key, you need to provide as 5th and last parameter an array with 2 keys:

  • c: the local path to the certificate (yourpublickey.crt).
  • p: permissions (the same structure as the first parameter) within an array.

A PDF signed with a public key, should be created using the following code:

$pdf->SetProtection(null,null,null,0, array(
    'c' => '/path/to/self-signed-certificate.crt',
    'p' => array('print','modify')
));

Example of protected PDF

As mentioned previously, in order to protect your PDF you need to pay attention to the SetProtection method and you're ready to go.

<?php

//require __DIR__ . '/vendor/autoload.php';
// we supposed that you know how to include the TCPDF class in your document

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

/**
 * Protect PDF from being printed, copied or modified. In order to being viewed, the user needs
 * to provide "ourcodeworld" as password.
 */
$pdf->SetProtection(array('print', 'copy','modify'), "ourcodeworld", "ourcodeworld-master", 0, null);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Our Code World');
$pdf->SetTitle('TCPDF Example');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 016', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(array('helvetica', '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(array('helvetica', '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// add a page
$pdf->AddPage();

// set some text to print
$txt = <<<EOD
Encryption Example

Consult the source code documentation for the SetProtection() method.
EOD;

// print a block of text using Write()
$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);

//Close and output PDF document to the browser
$pdf->Output('example_016.pdf', 'I');

You can see an official demo in the TCPDF website about encryption of a PDF here or read the documentation of the TCPDF class. Have fun!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors