How can PHP be used to create and modify existing PDF files?

To create and modify existing PDF files using PHP, you can use libraries like TCPDF or FPDI. TCPDF allows you to create new PDF files from scratch, while FPDI enables you to import existing PDF files and modify them. By combining these libraries, you can both create new PDF files and manipulate existing ones in PHP.

// Example using TCPDF to create a new PDF file
require_once('tcpdf/tcpdf.php');

$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(0, 10, 'Hello World!', 0, 1, 'C');
$pdf->Output('new_pdf_file.pdf', 'F');

// Example using FPDI to import and modify an existing PDF file
require_once('fpdi/fpdi.php');

$pdf = new FPDI();
$pageCount = $pdf->setSourceFile('existing_pdf_file.pdf');
for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) {
    $templateId = $pdf->importPage($pageNumber);
    $pdf->AddPage();
    $pdf->useTemplate($templateId, 10, 10, 200);
    $pdf->SetFont('Arial', '', 12);
    $pdf->SetTextColor(255, 0, 0);
    $pdf->SetXY(10, 200);
    $pdf->Write(0, 'Page ' . $pageNumber);
}
$pdf->Output('modified_pdf_file.pdf', 'F');