bulletThe ID Security Suite News Archive is being updated on regular basis, so please check in from time to time for up to date articles on PC Security issues.

Password protect a PDF document in PHP

07 Oct 2008
 by Cristina Mailat | in: News, Security

Check bellow the solution I found for on the fly protecting a PDF file in PHP. For resolving this problem I wanted a FREE library. Download the library used: Protect PDF in PHP from and use the code bellow for password protect a PDF file using PHP.

<?php

function pdfEncrypt ($origFile, $password, $destFile){
//include the FPDI protection http://www.setasign.de/products/pdf-php-solutions/fpdi-protection-128/
require_once(‘fpdi/FPDI_Protection.php’);

$pdf =& new FPDI_Protection();
// set the format of the destinaton file, in our case 6×9 inch
$pdf->FPDF(‘P’, ‘in’, array(’6′,’9′));

//calculate the number of pages from the original document
$pagecount = $pdf->setSourceFile($origFile);

// copy all pages from the old unprotected pdf in the new one
for ($loop = 1; $loop <= $pagecount; $loop++) {
$tplidx = $pdf->importPage($loop);
$pdf->addPage();
$pdf->useTemplate($tplidx);
}

// protect the new pdf file, and allow no printing, copy etc and leave only reading allowed
$pdf->SetProtection(array(), $password, ”;
$pdf->Output($destFile, ‘F’);

return $destFile;
}

//password for the pdf file (I suggest using the email adress of the purchaser)
$password = “info@domain.com”;

//name of the original file (unprotected)
$origFile = “book.pdf”;

//name of the destination file (password protected and printing rights removed)
$destFile =“book_protected.pdf”;

//encrypt the book and create the protected file
pdfEncrypt($origFile, $password, $destFile );
?>

Published: 07 Oct 2008  by Cristina Mailat, in: News, Security Tags: , , RSS feed for comments on this post.

20 Responses to “Password protect a PDF document in PHP”

  1. I found the original script (found at http://www.fpdf.org/en/script/script37.php) a lot easier to handle. It only required minor changes to my code. No hassling with multiple files required!

    The only changes in my code were:
    require(“../fpdf/fpdf_protect.php”); // instead of fpdf.php

    class mijnPDF extends FPDF_Protection // instead of … extends FPDF

    $pdf = new mijnPDF();
    $pdf->SetProtection(array(‘print’)); // line added after the creation of my proper PDF class based on FPDF

  2. Hello, I corrected the code, now you is just copy paste:

    FPDF(‘P’, ‘in’, array(’6′,’9′));

    //calculate the number of pages from the original document
    $pagecount = $pdf->setSourceFile($origFile);

    // copy all pages from the old unprotected pdf in the new one
    for ($loop = 1; $loop importPage($loop);
    $pdf->addPage();
    $pdf->useTemplate($tplidx);
    }

    // protect the new pdf file, and allow no printing, copy etc and leave only reading allowed
    $pdf->SetProtection(array(),$password);
    $pdf->Output($destFile,’F');

    return $destFile;
    }

    //password for the pdf file (I suggest using the email adress of the purchaser)
    $password = ‘info@domain.com’;

    //name of the original file (unprotected)
    $origFile = ‘book.pdf’;

    //name of the destination file (password protected and printing rights removed)
    $destFile =’book_protected.pdf’;

    //encrypt the book and create the protected file
    pdfEncrypt($origFile, $password, $destFile );
    ?>

  3. hi!

    the code is great!

    i used it and it works!

    i have now security in my pdf reports.

    but i notice the print button is disabled.
    i try to fix it but i failed.

    can you guys give me a help?

    thanks a lot!

  4. use
    $pdf->SetProtection(array(‘print’),”password”);

  5. Hello Guys,

    I tried to implement it in my site but it failed.
    The right portion of my original pdf is cropped out when it is saved with password protection. Why its happening. Can anyone help in this

    -rahul

  6. Hey Arthur,

    To get allow printing replace the line:
    $pdf->SetProtection(array(), $password, “”);

    With
    $pdf->SetProtection(array(‘print’ => ‘print’), $password, “”);

    Should do the trick for you.

    Cristina,

    Is there a way to allow input into this script and not having to set the page format? It will default to landscape A4, but is there a way getting it to auto-detect the dimensions of the PDF that I am putting in?

    Many thanks,

    James Doc

  7. I read all those comments, but none relate the fact that on a PC, setting ‘print’ allows printing + saving the document and no editing, while on a MAC, only printing is allowed…. All I awant is to allow “print” and “Save as” with no password when the destination computer is a MAC. Any idea someone …. thanks in advance

    M

  8. I have the same question as James Doc,

    Is there a way to allow input into this script and not having to set the page format? It will default to landscape A4, but is there a way getting it to auto-detect the dimensions of the PDF that I am putting in?

  9. I tried but failed.. Where the errors?..

    FPDF(‘P’, ‘in’, array(’6′,’9′));

    //calculate the number of pages from the original document
    $pagecount = $pdf->setSourceFile($origFile);

    // copy all pages from the old unprotected pdf in the new one
    for ($loop = 1; $loop importPage($loop);
    $pdf->addPage();
    $pdf->useTemplate($tplidx);
    }

    // protect the new pdf file, and allow no printing, copy etc and leave only reading allowed
    $pdf->SetProtection(array(), $password, ”;
    $pdf->Output($destFile, ‘F’);

    return $destFile;
    }

    //password for the pdf file (I suggest using the email adress of the purchaser)
    $password = “info@domain.com”;

    //name of the original file (unprotected)
    $origFile = “book.pdf”;

    //name of the destination file (password protected and printing rights removed)
    $destFile =“book_protected.pdf”;

    //encrypt the book and create the protected file
    pdfEncrypt($origFile, $password, $destFile );
    ?>

  10. hi Jose , there is for loop error in your code right ?

  11. I’m doing an online calendar generator as pdfs but encrypting files it takes forever at least 5-10 times more than raw pdf version. I believe a more practical method will be to stamp every month file. But with a powerfull enough online system and with just few users trying to generate pdfs it may be acceptable.
    I guess encrypting images take a lot more processing power and time than simply aplying password to text only documents.

  12. The FPDI-Encryption (40 bit) is not very secure.
    It’s “cracked” in about 5-10 Minutes.

  13. Hi,
    I have this code below to create a pdf on the fly and send as an email attachment. I like to make it password protected for open and everything. Is there any way I could use your code?

    // download fpdf class (from fpdf.org)
    require(“fpdf/fpdf.php”);

    // fpdf object
    $pdf = new FPDF();

    // generate a simple PDF (for more info, see http://fpdf.org/en/tutorial/)
    $pdf->AddPage();
    $pdf->SetFont(“Arial”,”B”,14);
    $pdf->Cell(40,10, “this is a pdf example”);

    // email stuff (change data below)
    $to = “info@XXXXX.com”;
    $from = “info@XXXXXX.com”;
    $subject = “send email with pdf attachment”;
    $message = “Please see the attachment.”;

    // a random hash will be necessary to send mixed content
    $separator = md5(time());

    // carriage return type (we use a PHP end of line constant)
    $eol = PHP_EOL;

    // attachment name
    $filename = “bookingrequest.pdf”;

    // encode data (puts attachment in proper format)
    $pdfdoc = $pdf->Output(“”, “S”);
    $attachment = chunk_split(base64_encode($pdfdoc));

    // main header (multipart mandatory)
    $headers = “From: “.$from.$eol;
    $headers .= “MIME-Version: 1.0″.$eol;
    $headers .= “Content-Type: multipart/mixed; boundary=\”".$separator.”\”".$eol.$eol;
    $headers .= “Content-Transfer-Encoding: 7bit”.$eol;
    $headers .= “This is a MIME encoded message.”.$eol.$eol;

    // message
    $headers .= “–”.$separator.$eol;
    $headers .= “Content-Type: text/html; charset=\”iso-8859-1\”".$eol;
    $headers .= “Content-Transfer-Encoding: 8bit”.$eol.$eol;
    $headers .= $message.$eol.$eol;

    // attachment
    $headers .= “–”.$separator.$eol;
    $headers .= “Content-Type: application/octet-stream; name=\”".$filename.”\”".$eol;
    $headers .= “Content-Transfer-Encoding: base64″.$eol;
    $headers .= “Content-Disposition: attachment”.$eol.$eol;
    $headers .= $attachment.$eol.$eol;
    $headers .= “–”.$separator.”–”;

    // send message
    mail($to, $subject, “”, $headers);

  14. We used this api to protect the pdf file while uploading. It works on Windows machine, but, when the file opened in MAC machine it’s not asking for the password.. any help?

  15. When I encrypted the file it is opening with out asking for password on Mac
    Is that normal? Am I missing something?

  16. Hi, i´ve implemented it, and it works so fine, but i would like to know, how to increase the security if the 40 bits isn´t.

  17. I am not able to view the page.Plz guide where is the error… Below is my code

    function pdfEncrypt ($origFile, $password, $destFile){
    require_once(‘fpdi/FPDI_Protection.php’);
    $pdf =& new FPDI_Protection();
    $pdf->FPDF(‘P’, ‘in’,array(’6′,’9′));
    //Calculate the number of pages from the original document.
    $pagecount = $pdf->setSourceFile($origFile);
    //Copy all pages from the old unprotected pdf in the new one.
    for ($loop = 1; $loop importPage($loop);
    $pdf->addPage();
    $pdf->useTemplate($tplidx);
    }

    //Protect the new pdf file, and allow no printing, copy, etc. and
    //leave only reading allowed.
    $pdf->SetProtection(array(), $password);
    //$pdf->SetProtection(array(‘print’ => ‘print’), $password, “”);
    $pdf->Output($destFile, ‘F’);
    return $destFile;

    }

    //Password for the PDF file (I suggest using the email adress of the purchaser).
    $password = “password”;
    //Name of the original file (unprotected).
    $origFile = “abc.pdf”;//”sample.pdf”;
    //Name of the destination file (password protected and printing rights removed).
    $destFile =”xyz.pdf”;
    //Encrypt the book and create the protected file.
    pdfEncrypt($origFile, $password, $destFile );

  18. when i try to use this example i have this error:

    FPDF error: Unknown box: /CropBox

    what is the problem?
    thanx

  19. [...] files from editing (in my case, print protect is also possible). After doing some research I found this class from ID Security Suite. First of all I have to say – IT’S OLD (I am running PHP 5+). [...]

Leave a Reply