Skip to content

Instantly share code, notes, and snippets.

@niraj-shah
Last active August 15, 2018 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niraj-shah/36223019f7a9bd1dedfecd771c1d2d1d to your computer and use it in GitHub Desktop.
Save niraj-shah/36223019f7a9bd1dedfecd771c1d2d1d to your computer and use it in GitHub Desktop.
Password Protecting PDFs using PHP
<?php
require "PasswordProtectPDF.php";
try {
$pdf = new PasswordProtectPDF("test.pdf", "mypassword");
// render the PDF inline (i.e. within browser where supported)
$pdf->setTitle("Test PDF")->output('I', 'test.pdf');
} catch (\Exception $e) {
// catch any errors in rendering the PDF
if ($e->getCode() == 267) {
die('The compression on this file is not supported.');
}
die('There was an error generating the PDF.');
}
exit;
$pdf = new PasswordProtectPDF("test.pdf", "mypassword");
// force the PDF to download to filename specified
$pdf->setTitle("Test PDF")->output('D', 'test.pdf');
exit;
$pdf = new PasswordProtectPDF("test.pdf", "mypassword");
// save PDF as file on the server
$pdf->setTitle("Test PDF")->output('F', 'test.pdf');
exit;
<?php
require "vendor/autoload.php";
use setasign\Fpdi\Fpdi;
use setasign\Fpdi\PdfReader;
use setasign\FpdiProtection\FpdiProtection;
class PasswordProtectPDF
{
protected $pdf = null;
public function __construct($file, $user_pass, $master_pass = null)
{
$this->protect($file, $user_pass, $master_pass);
}
public function protect($file, $user_pass, $master_pass = null)
{
$pdf = new FpdiProtection();
// set the source of the PDF to protect
$pagecount = $pdf->setSourceFile($file);
// copy all pages from the old unprotected pdf in the new one
for ($i = 1; $i <= $pagecount; $i++) {
// import each page from the original PDF
$tplidx = $pdf->importPage($i);
// get the size, orientation etc of each imported page
$specs = $pdf->getTemplateSize($tplidx);
// set the correct orientatil, width and height (allows for mixed page type PDFs)
$pdf->addPage($specs['orientation'], [ $specs['width'], $specs['height'] ]);
$pdf->useTemplate($tplidx);
}
// set user and master passwords, and allowed permissions
// the master password allows the PDF to be unlocked for full access
$pdf->SetProtection([ FpdiProtection::PERM_PRINT, FpdiProtection::PERM_DIGITAL_PRINT ], $user_pass, $master_pass);
// set app name as creator
$pdf->SetCreator("My Awesome App");
$this->pdf = $pdf;
return $this;
}
public function setTitle($title)
{
// set the title of the document
$this->pdf->SetTitle($title);
return $this;
}
public function output($name, $type = 'I')
{
// output the document
if ($type === 'S') {
return $this->pdf->Output($type, $name);
} else {
$this->pdf->Output($type, $name);
}
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment