How to generate password protected or Encrypted PDF using PHP

Let us discuss about password protect OR encrypted PDF using PHP

  1. So for First you need to download from git TCPDF library.
  2. After that create a create a index.html and pdf.php File in your root directory

In index.html

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>PHP PDF Generate</title>
  
<link rel='stylesheet' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div class="container-fluid itinfotech-builder">
		<h1>Generate Password Protect PDF Using PHP</h1>
	<form name="pdf_with_password" name="pdf_with_password" action="pdf.php" method="post">
		<div class="row">
				<div class="col-sm-12 loc_form">

						<div class="row">
								<div class="col-sm-4">
									<div class="form-group">
											<label for="title" class="control-label">Title</label>
											<input required class="form-control" id="title" name="title" placeholder="Main title" value="Really incredible!!" maxlength="255" type="text" tabindex="2">
									</div>
								</div>
								<div class="col-sm-3">
									<div class="form-group">
											<label for="title-size" class="control-label">Size P(PORTRAIT),L(LANDSCAPE)</label>
											<select required class="form-control" id="title-size" name="title_size">
												<!-- P(PORTRAIT),L(LANDSCAPE)],FORMAT(A4-A5-LETTER) -->
												<option value="A4(L)">A4(L)</option>
												<option value="A4(P)">A4(P)</option>											
												<option value="A5(P)">A5(P)</option>
												<option value="A5(L)">A5(L)</option>
												<option value="LETTER(P)">LETTER(P)</option>
												<option value="LETTER(L)">LETTER(L)</option>												
											</select>
											
									</div>
								</div>
								<div class="col-sm-2">
									<div class="form-group">
											<label for="title-color" class="control-label">Color</label>
											<input required class="form-control" id="title-color" name="title_color"  value="#0080FF" type="color" tabindex="4" title="Title color">
									</div>
								</div>
								<div class="col-sm-2">
										<div class="form-group">
												<label for="password" class="control-label">Password</label>
												<input  class="form-control" id="password" name="password" value="itinfotech123" type="text" />
										</div>
									</div>
						</div>

						<div class="form-group">
								<label class="control-label" for="description">Description</label>
								<textarea class="form-control" id="description" name="description" placeholder="Insert a short description taking care of the available space">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nemo, nihil officia neque ad expedita consequatur quae! Voluptate, incidunt, earum, sit, eveniet harum ratione expedita quibusdam possimus sed laboriosam dolore ut recusandae eos. Ipsa,natus pariatur iste dolorum optio nostrum consectetur!</textarea>
						</div>

						<hr>
						<div class="row">
								<div class="col-sm-6">
										<div class="form-group">
												<button id="genrate_pdf" name="genrate_pdf" value="I"
												type="submit" class="btn btn-primary btn-block" tabindex="9">Update preview</button>
										</div>
								</div>
								<div class="col-sm-6">
										<div class="form-group text-right">
												<button id="genrate_pdf" name="genrate_pdf" value="D" type="submit" class="btn btn-default btn-xs btn-block" tabindex="10">Download</button>
										</div>
								</div>
						</div>
						<div class="row">
						<div class="col-sm-12">
								
		<p><em><a target="_blank"  href="">Download Code to click here</a>	Demo design to create a password protected PDF using TCPDF PHP library.
				<a target="_blank"  href="https://github.com/tecnickcom/TCPDF">Download library From GIT</a></em></p>
							<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
							<!-- password-protected-pdf -->
							<ins class="adsbygoogle"
								style="display:block"
								data-ad-client="ca-pub-3403758495591879"
								data-ad-slot="7461742800"
								data-ad-format="auto"
								data-full-width-responsive="true"></ins>
							<script>
								(adsbygoogle = window.adsbygoogle || []).push({});
							</script>
						</div>
					</div>

				</div>
		</div>
	</form>
</div>
<!-- partial -->
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

</body>
</html>

In pdf.php

The permission array is composed of values taken from the following ones
(specify the ones you want to block): –

-print : Print the document;

-modify : Modify the contents of the document by operations other than those controlled by
‘fill-forms’, ‘extract’ and ‘assemble’;

-copy : 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.

If you don’t set any password, the document will open as usual.
If you set a user password, the PDF viewer will ask for it before
displaying the document. The master (owner) password, if different from the user one, can be used to get full document access.

 Possible encryption modes are:    0 = RSA 40 bit    1 = RSA 128 bit    2 = AES 128 bit    3 = AES 256 bit

 NOTES: – To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt – To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12 – To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes

<?php
require_once 'vendor/autoload.php'; 
if(count($_POST)>0 && !empty($_POST['title']) && !empty($_POST['title_size']) && !empty($_POST['title_color']) && !empty($_POST['description']) && !empty($_POST['genrate_pdf']))
{
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

if(isset($_POST['password']) && !empty($_POST['password']))
{
$pdf->SetProtection(array('print', 'copy','modify'), $_POST['password'], $_POST['password'], 0, null);
}

$pdf->SetCreator('TCPDF');
$pdf->SetAuthor('IT-INFOTECH');
$pdf->SetTitle('TCPDF Password Protect PDF');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, Password-Protect, itinfotech');

$pdf->SetHeaderData('itinfotech_logo.png', 30, $_POST['title'].' 016', 'by Admin - Demot tutorial');

$pdf->setHeaderFont(Array('helvetica', '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array('helvetica', '', PDF_FONT_SIZE_DATA));

$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
	require_once(dirname(__FILE__).'/lang/eng.php');
	$pdf->setLanguageArray($l);
}

$pdf->SetFont('times', '', 16);

$page=explode("(",$_POST['title_size']);
$pdf->AddPage($page[1],$page[0]);

$color=$_POST['title_color'];

$txt = '<span style="color:'.$color.'">'.$_POST['description'].'</span>
';

$pdf->writeHTML($txt, true, false, true, false, '');

$pdf->Output('example_password_protect_pdf.pdf', $_POST['genrate_pdf']);
}

?>

Add a Comment

Your email address will not be published. Required fields are marked *