Good morning, I'm trying to make an algorithm that takes several images and several PDFs and converts them into a single PDF, making it easier to upload files to my system.
I have the following codes:
$pdf = new FPDF();
$Fpdfi = new setasign\Fpdi\Fpdi();
foreach ($uploaded_files as $file) {
ob_start();
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) {
$pdf->AddPage();
$pdf->Image($file);
} elseif ($extension == 'pdf') {
$pdf->AddPage();
$pdf->SetFont('Arial', '', 12);
$pdf->MultiCell(0, 5, "PDF file: $file");
$pdf->AddPage();
$Fpdfi->setSourceFile($file);
$tplIdx = $Fpdfi->importPage(1);
$Fpdfi->useTemplate($tplIdx, 10, 10, 90); }
ob_end_flush();
}
$output_file = $uploads_dir . '/result.pdf';
$pdf->Output('F', $output_file);
When it gets to the line $Fpdfi->useTemplate($tplIdx, 10, 10, 90);
it returns the following error:
Uncaught Exception: FPDF error: No page has been added yet in
C:...\plugins\fpdf\fpdf.php:273
Stack trace: #0 C:...\plugins\fpdf\fpdf.php(1464):
FPDF->Error('No page has bee...') #1
C:\xampp...\plugins\Fpdi\FpdfTplTrait.php(467):
FPDF->_out('q 0 J 1 w 0 j 0...') #2
C:...\plugins\Fpdi\FpdiTrait.php(441):
setasign\Fpdi\FpdfTpl->_out('q 0 J 1 w 0 j 0...') #3
C:...\plugins\Fpdi\Fpdi.php(59):
setasign\Fpdi\Fpdi->useImportedPage('C:\xampp\htdocs...', 10, 10, 90, NULL, false) #4
C:...\themes\easy\testeapi\teste_pdf.php(56):
setasign\Fpdi\Fpdi->useTemplate('C:\xampp\htdocs...', 10, 10, 90) #5
C:...\wp-includes\template-loader.php(74): include('C:\...\plugins\fpdf\fpdf.php on line 273
OBS: this only happens when I try to attach the PDF, if I only use Images, it works very well
I did several tests, and several searches including using ChatGPT, but I still couldn't reach the expected. the idea is to upload x files (PDF and IMAGE), and transform them into a single PDF.