Is it possible to merge multiple PDF files into one document using PHP?
Yes, it is possible to merge multiple PDF files into one document using PHP. One way to achieve this is by using the `FPDI` library in combination with `FPDF`. First, you need to install the library using Composer. Then, you can loop through each PDF file, import it using `FPDI`, and add it to a new PDF document using `FPDF`.
// Install FPDI library using Composer
// composer require setasign/fpdi
require_once('vendor/autoload.php');
use setasign\Fpdi\Fpdi;
// Array of PDF files to merge
$pdfFiles = ['file1.pdf', 'file2.pdf', 'file3.pdf'];
// Initialize new FPDF instance
$pdf = new Fpdi();
// Merge PDF files
foreach ($pdfFiles as $file) {
$pageCount = $pdf->setSourceFile($file);
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$templateId = $pdf->importPage($pageNo);
$size = $pdf->getTemplateSize($templateId);
$pdf->AddPage($size);
$pdf->useTemplate($templateId);
}
}
// Output merged PDF
$pdf->Output('merged_file.pdf', 'F');
Keywords
Related Questions
- What is the correct syntax for fetching and accessing data from a MySQL query result in PHP?
- What are some common methods for handling links and anchor tags in PHP when generating HTML content?
- Is it better to have separate PHP files for different purposes or combine them into one large file or class for performance reasons?