Fpdi Error Message: Page number "3" out of available page range (1 - 2)

74 Views Asked by At

I am working in codeigniter 3 and using FPDI library to merge multiple pdf into single. But getting error at this line $tplIdx = $pdf->importPage($i); . I had tried to fix this with different ways but nothing is working. Below is my code

function generateSinglePdf($List)
{
$pdfValue = explode(',',$List);
$path = $file = FCPATH."createpdf/";
foreach($pdfValue as $pdfVal)
{
foreach(glob("$path/{$pdfVal}*") as $imgfile)
{

$ext = substr(strrchr($imgfile, '.'), 1);
if($ext=='pdf')
{
    $imgName[] = basename($imgfile);

}   

}

}   
$count = count($imgName);
$filelocation = FCPATH."/newmultigenerate";
$time = date("d-m-Y")."-".time();
$mainfilename="ID".$id."-multipdf-".$time;
$filename=$mainfilename.".pdf";
$fileNL = $filelocation."/".$filename;

$pdf = new MPdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('OrderCal');
$pdf->SetSubject('Invoice Pdf');
$pdf->SetKeywords('Invoice Pdf');
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(2, 10, 2,true);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, 10);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->SetFont('times', 'BI', 10);
$pdf->my_header_title = '';


for($i=0; $i<=$count;$i++)
{
if($imgName[$i]=="")
continue;
$imgUrl =  FCPATH."createpdf/".$imgName[$i];
$pdf->setSourceFile($imgUrl);
$tplIdx = $pdf->importPage($i);
$pdf->useTemplate($tplIdx);

}   

$pdf->Output($fileNL, 'F');
}
1

There are 1 best solutions below

2
user2222 On

I have changed this in my code and it's working now. We need to run loop of images array and then in loop need to count image one by one. In my above code image count was wrong.

foreach($imgName as $val)
{
$imgUrl =  FCPATH."createpdf/".$val;
$cnt = $pdf->setSourceFile($imgUrl);
for($i=1; $i<=$cnt;$i++)
{

$pdf->AddPage();
$tplIdx = $pdf->importPage($i);
$pdf->useTemplate($tplIdx);
}   

} 

$pdf->Output($fileNL, 'F');