Generating mutliple pdf files using mpdf but only one is generated - php

I want to generate multiple files using mpdf library, but unfortunately, only one file is generated, instead of multiple, how can I do this. Thanks for showing your interest.
for ($i=1; $i<count($sheetData); $i++)
{
$name = $sheetData[$i][0];
$fName = $sheetData[$i][1];
$mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => [290, 236]]);
$stylesheet = file_get_contents('../assets/css/style.css');
$mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);
ob_end_clean();
$html = $mpdf->WriteHTML('<p>My Layout is there</p>');
$filename = time().'.pdf';
$mpdf->Output($filename ,'D');
unset($mpdf);
}

You need to save them. U cant output them all at once with "D" or "I"
$mpdf->Output($filename ,'F');
if need one file with addPage() https://mpdf.github.io/reference/mpdf-functions/addpage.html
$mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => [290, 236]]);
for ($i = 1; $i < count($sheetData); $i++) {
$name = $sheetData[$i][0];
$fName = $sheetData[$i][1];
$stylesheet = file_get_contents('../assets/css/style.css');
if ($i > 1) {
$mpdf->AddPage();
}
$mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);
$mpdf->WriteHTML('<p>My Layout is there</p>');
}
$filename = 'my.pdf';
$mpdf->Output($filename, 'F');
u can also create html first
$mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => [290, 236]]);
$html = '';
for ($i = 1; $i < count($sheetData); $i++) {
$name = $sheetData[$i][0];
$fName = $sheetData[$i][1];
$html .= '<p>My Layout is there</p>';
}
$stylesheet = file_get_contents('../assets/css/style.css');
$mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);
$mpdf->WriteHTML($html);
$filename = 'my.pdf';
$mpdf->Output($filename, 'D');

Do you want to send multiple PDF files to the client or to save them on disk?
You're using time() as a pseudo-random filename, but if the generation of the PDF files is fast enough and happens in the same second, you will overwrite the previously generated file, at least if you choose to store the resulting file on disk. You may want to use something like "generated_$i" instead of time().

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";
?>

PHP FPDI Try to add text in Hebrew language to pdf file but i got problem in utf

I use FPDI library for php and try to add text into pdf file.
It's work but when i change the text to Hebrew i got
×•× ̈×– הצלח×a×TM להוס×TM×£ × ̃×§×¡× ̃
This is my code:
<?php
use setasign\Fpdi\Fpdi;
use \setasign\Fpdi\PdfParser\StreamReader;
require_once('fpdf/fpdf.php');
require_once('fpdi/src/autoload.php');
$rawPostBody = file_get_contents('php://input');
$signatures = (array)json_decode($rawPostBody);
$fileURL = $signatures['filURL'];
$signaturesData = $signatures['signatures'];
// Initial Fpdi
$pdf = new Fpdi();
// Load external pdf file with StreamReader (We Use StreamReader Only for External file)
$fileContent = file_get_contents($fileURL,'rb');
$pdf->setSourceFile(StreamReader::createByString($fileContent));
// Get number of pages.
$pageCount = $pdf->setSourceFile(StreamReader::createByString($fileContent));
// Illiterate and create pdf pages.
for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) {
$tplId = $pdf->importPage($pageNumber);
$s = $pdf->getTemplatesize($tplId);
$pdf->SetTextColor(0,0,0);
$pdf->SetFont('Arial','B',10);
$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L', array($s['w'], $s['h'])); // This gets it the right dimensions
$pdf->useTemplate($tplId, null, null, null, null, true);
foreach ($signaturesData as $signa) {
if($signa->page == $pageNumber) {
$pdf->SetXY(number_format($signa->positionX), number_format($signa->positionY * 0.264583));
$pdf->Write(0, "שלום שלום");
}
}
}
$pdf->Output('pdf-with-value.pdf', 'D');
I read some post with a similar problem but I couldn't figure out what exactly I needed to do.
Thanks
I found solution, first I download hebrew font then i put the files in font folder then:
$pdf->AddFont('Rubik-Light', '', 'Rubik-Light.php');
$pdf->SetFont('Rubik-Light', '', 15);
$value = iconv('UTF-8', 'windows-1255', html_entity_decode('עובד פיקס'));
$value = strrev($value);
$pdf->Write(0, $value);

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.

Import page from external PDF file can't display properly

The PDF file have a large width than normal.
$pagecount = $mpdf->SetSourceFile($pdfurl);
for($x=0;$x<$pagecount;$x++){
$tplId = $mpdf->ImportPage(($x+1));
$mpdf->UseTemplate($tplId);
$mpdf->AddPage();
}
Most PDF is displayed well, but with large width, it only display a part of it.
There are several issues in your code:
You call UseTemplate() before you have added a page.
The AddPage() method adds a page in the default page size, which was defined in the constructor.
So you have to change your script to:
$pageCount = $mpdf->SetSourceFile($pdfurl);
for($pageNo = 1; $pageNo <= $pageCount ; $pageNo++){
$tplId = $mpdf->ImportPage($pageNo);
$size = $mpdf->GetTemplateSize($pageNo);
$mpdf->AddPageByArray([
'orientation' => $size['w'] > $size['h'] ? 'L' : 'P',
'newformat' => [$size['w'], $size['h']]
]);
$mpdf->UseTemplate($tplId);
}
Thanks #Jan.Your code not work perfectly for me.But point me the right direction.
for($pageNo = 1; $pageNo <= $pageCount ; $pageNo++){
$tplId = $mpdf->ImportPage($pageNo);
$size = $mpdf->GetTemplateSize($tplId);
$w=210;
if($size['w'] > $size['h']){
$w=299;
}
$mpdf->AddPageByArray([
'orientation' => $size['w'] > $size['h'] ? 'L' : 'P'
]);
$mpdf->UseTemplate($tplId,0,0,$w);
}
But my solution got a problem.The landscape mode will scale the PDF size a little small.

Merging PDF files with PHP/FPDI

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.

Categories