Merging PDF files with PHP/FPDI - php

i am trying to merge two files using FPDI the error i get is:'TCPDF ERROR: File is encrypted!', however, the files are not encrypted, at least the files are printable, viewable etc and no password is required.
i want to merge two files:
http://www.nps.org.au/__data/cmi_pdfs/CMI7412.pdf
http://www.nps.org.au/__data/cmi_pdfs/CMI6656.pdf
after i copy the files to the server and store the file names in array ($files) that has the absolute file paths, my code is:
if (count ($files) > 0 )
{
$pdf = new FPDI();
$pdf->setPrintHeader(FALSE);
$pdf->setPrintFooter(FALSE);
foreach ($files as $file)
{
for ($i = 0; $i < count($files); $i++ )
{
$pagecount = $pdf->setSourceFile($files[$i]);
for($j = 0; $j < $pagecount ; $j++)
{
$tplidx = $pdf->importPage(($j +1), '/MediaBox');
$specs = $pdf->getTemplateSize($tplidx);
if ( $specs['h'] > $specs['w'] )
{
$orientation = 'P';
}
else
{
$orientation = 'L';
}
$pdf->addPage($orientation,'A4');
$pdf->useTemplate($tplidx, 0, 0, 0, 0, TRUE);
}
}
$output = $pdf->Output('', 'S');
foreach ( $files as $file )
{
delete_file($file);
}
}
I have also tried to merge the files using ghostscript, but with no luck.
I tried acrobat pro, which required a password for one file, but when I used mac preview, i exported the file and was able to merge it using acrobat with no issues. i.e. mac preview removed the protection with no problems.
So, what is it about the file CMI7412.pdf that stops merging, but not exporting, viewing, printing? and how can i get around it?

I have tried similar issue and works fine, try it. It can handle different orientations between PDFs.
// array to hold list of PDF files to be merged
$files = array("a.pdf", "b.pdf", "c.pdf");
$pageCount = 0;
// initiate FPDI
$pdf = new FPDI();
// iterate through the files
foreach ($files AS $file) {
// get the page count
$pageCount = $pdf->setSourceFile($file);
// iterate through all pages
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
// create a page (landscape or portrait depending on the imported page size)
if ($size['w'] > $size['h']) {
$pdf->AddPage('L', array($size['w'], $size['h']));
} else {
$pdf->AddPage('P', array($size['w'], $size['h']));
}
// use the imported page
$pdf->useTemplate($templateId);
$pdf->SetFont('Helvetica');
$pdf->SetXY(5, 5);
$pdf->Write(8, 'Generated by FPDI');
}
}

The problem was the encryption in the pdf file, it was protected from changes without a password.
I used qpdf to export a decrypted version of the pdf as a temporary file. Then I used pdftk to join the files. Turns out to be far faster than the PHP libraries.

Related

how delete one page from pdf by imagemagick

i m Wana Delete One page from PDF By imagemagick , How can this be done? this my code this return just one page in pdf ? what the problem ?
$image = new \Imagick(__DIR__.'/test.pdf');
$pageNumber = $image->count();
$page = true;
$imgs = [];
for($i=0 ; $i<$pageNumber ; $i++){
$image->readImage(__DIR__.'/test.pdf['.$i.']');
if($i === 2 && $page == true){
$image->removeImage();
$page = false;
continue;
}
// $imgs[] = __DIR__.'images'.$i.'.jpg';
}
$image->setImageFormat("pdf");
$image->writeImage('images.pdf');
file_put_contents(__DIR__.'images'.$i.'.pdf',$image);
Assuming that the original pdf is having 5 pages (known as fivepage.pdf), then you may use the following steps to remove page 3 from it and generate a new pdf known as combined.pdf
use Imagick to open the pdf
determine the number of pages
loop over each page of this pdf
save the pages into separate , temporary jpeg files
push the jpeg files (except page 3, $i==2) into array
use the array to generate the "combined.pdf"
delete all the temp jpeg files
So the code is:
<?php
$file="./fivepage.pdf";
$im = new Imagick($file);
$resultimages = array();
$noOfPagesInPDF = $im->getNumberImages();
// loop over all the pdf pages
for ($i = 0; $i < $noOfPagesInPDF; $i++) {
$url = $file.'['.$i.']';
$image = new Imagick();
// $image->setResolution(300,300);
// use the above line if you want higher resolution
$image->readimage($url);
$image->setImageFormat("jpg");
$image->writeImage("./temp_".($i+1).'.jpg');
// include all pages except page 3 ($i==2)
if ($i!=2) {
array_push($resultimages, "./temp_".($i+1).'.jpg');
}
}
// generate the resulting pdf (omitting page 3)
$pdf = new Imagick($resultimages);
$pdf->setImageFormat('pdf');
$pdf->writeImages('combined.pdf', true);
// clear temp images
for ($i = 0; $i < $noOfPagesInPDF; $i++) {
unlink("./temp_".($i+1).'.jpg');
}
echo "pdf without page 3 saved";
?>

Double signature on pdf already signed

I have this script which already sign a PDF
<?php
require("../config/include.php");
require_once(DIR_LIBRERIAS."TCPDF/tcpdf.php");
require_once(DIR_LIBRERIAS.'FPDI/fpdi.php');
//$pdf = new TCPDF(PDF_PAGE_ORIENTATION);
error_reporting(0);
// set certificate file
$certificate = 'file://'.DIR_ROOT.'cert/testcertif.crt';
$pdf = new FPDI();
$filename = "zz_test_firmado.pdf";
$info = array('Name' => 'testcertif', 'Location' => 'Oficina', 'Reason' => 'test firma', 'ContactInfo' => 'test.com.ar');
$pdf->setSignature($certificate, $certificate, 'test key pass', '', 2, $info);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pages_count= $pdf->setSourceFile($filename);
$page = "P";
for($i = 1; $i <= $pages_count; $i++)
{
$tplIdx = $pdf->importPage($i);
$size = $pdf->getTemplateSize($tplIdx);
if ($size['w'] > $size['h']) {
$pdf->AddPage('L', array($size['w'], $size['h']));
$arrayUltimo = array($size['w'], $size['h']);
$page = "L";
} else {
$pdf->AddPage('P', array($size['w'], $size['h']));
$arrayUltimo = array($size['w'], $size['h']);
}
$pdf->useTemplate($tplIdx, 0, 0, 0, 0, true);
}
$pdf->output('testfirmass222.pdf', 'I');
?>
However, when the pdf that i'm importing already has a signature, the signature is replaced by the new one put on the script, is there a way to keep both?
FPDI does not modify an original but you create a completely new one by importing page appearances of existing documents into a reusable structure.
The resulting document is a completely new one which may look identically but its internal structure is a completely different one.
Annotations and for sure digital signatures will not be imported.
Your task cannot be done with FPDI.
PS: In any case update FPDI to its latest version. It looks like you are using a legacy version.

how to add images to multiple pages on pdf and download the full pdf

I started to work with fpdi with fpdf and I try to add more than one image to multiple pages and in the end, I want to download one PDF with the images over the PDF pages.
The problem is that always just the last PDF downloaded with the last page. Why I can't download one file with all the images?
foreach ($signatures as $signa) {
$fileContent = file_get_contents('http://www.africau.edu/images/default/sample.pdf','rb');
$pageCount = $pdf->setSourceFile(StreamReader::createByString($fileContent));
$pdf->setSourceFile(StreamReader::createByString($fileContent));
$tplId = $pdf->importPage($signa->page);
$pdf->useTemplate($tplId, 10, 10, 100);
$pdf->Image('signature.jpg', $signa->position->x, $signa->position->y, $signa->size->width, $signa->size->height);
if($signa->page === 2) {
$pdf->Output('D');
}
}
I found this Solution and its work for me.
Solution on my code:
$pdf = new Fpdi();
foreach ($signatures as $signa) {
$pdf->AddPage();
$fileContent = file_get_contents('http://www.africau.edu/images/default/sample.pdf','rb');
$pdf->setSourceFile(StreamReader::createByString($fileContent));
$tplId = $pdf->importPage($signa->page);
$pdf->useTemplate($tplId, 10, 10, 100);
$pdf->Image('signature.png', $signa->position->x, $signa->position->y, $signa->size->width, $signa->size->height);
}
$pdf->Output('newpdf1.pdf', 'D');

TCPDF - Add "Bates Numbering" to merged PDF

I'm currently using TCPDI merge four documents into a single PDF and temporarily storing the document using a variable. Is it possible to add "Bates Numbering" to the file, starting with the third page? (The first two pages are a cover letter.) Thanks in advance for pointing me in the right direction
require_once('../tcpdf/tcpdf.php');
require_once('../tcpdf/tcpdi.php');
// Create new PDF document.
$pdf = new TCPDI();
// iterate through the files
foreach ($filesarray AS $file) {
// get the page count
$pageCount = $pdf->setSourceFile($file);
// iterate through all pages
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
// add a page with the same orientation and size
$pdf->AddPage($size['orientation'], $size);
// Set page boxes from imported page 1.
$pdf->setPageFormatFromTemplatePage($pageNo, $size['orientation']);
// use the imported page
$pdf->useTemplate($templateId);
}
}
// Output the new PDF
$attachment = $pdf->Output("Merged.pdf", "S");
I'm not familiar with Bates System but what i did was add the Page number as a Label and check your PageNo variable/index to determine when to show your batesNo.
For the labeling. See the TCPDF documentation.
*Code not tested
<?php
// iterate through the files
foreach ($filesarray AS $file) {
// get the page count
$pageCount = $pdf->setSourceFile($file);
$batesNo = 0000000001; //initialize*****
// iterate through all pages
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
/***********NEW BLOCK*******/
if ($pageNo > 3) {
$pdf->SetTitle('JonesNo-'.$batesNo);
} else {
$pdf->SetTitle($pageNo);
}
////////////////////////
// add a page with the same orientation and size
$pdf->AddPage($size['orientation'], $size);
// Set page boxes from imported page 1.
$pdf->setPageFormatFromTemplatePage($pageNo, $size['orientation']);
// use the imported page
$pdf->useTemplate($templateId);
}
}
?>

Convert Multip Page PDF in to single pages with PHP, Imagick ghost script

i have a pdf upload script with php, my question is when user uploads a multipage pdf file , i want this to split in to individual pdf's. for instance if the pdf has 3 pages, the result should be 1.pdf , 2.pdf, 3.pdf etc.
for example
convert -density 300 filename.pdf filename.png works fine creating a png file , but i want the same in to pdf files.
You can use a FPDF and FPDI to do this.
require_once('fpdf/fpdf.php');
require_once('fpdi/fpdi.php');
// get the page count
$pdf = new FPDI();
$pageCount = $pdf->setSourceFile($pdfFilePath);
// iterate through all pages
for($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++)
{
// create blank document
$pdf = new FPDI();
// import a page
$pdf->setSourceFile($pdfFilePath);
$templateId = $pdf->importPage($pageNumber);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
// create a page (landscape or portrait depending on the page being imported)
if($size['w'] > $size['h'])
{
$pdf->AddPage('L', array($size['w'], $size['h']));
}
else
{ $pdf->AddPage('P', array($size['w'], $size['h']));
}
// use the imported page
$pdf->useTemplate($templateId);
// write the PDF file
$pdf->Output(('/path/to/save/'.$pageNumber.'pdf'), 'F');
}

Categories