Wednesday, July 3, 2024
HomeLanguagesPhpHow to generate PDF file using PHP ?

How to generate PDF file using PHP ?

In this article, we will learn how to generate PDF files with PHP by using FPDF. It is a free PHP class that contains many functions for creating and modifying PDFs. The FPDF class includes many features like page formats, page headers, footers, automatic page break, line break, image support, colors, links, and many more.

Approach:

require('fpdf/fpdf.php');
  • Instantiate and use the FPDF class according to your need as shown in the following examples.
$pdf=new FPDF();

Example 1: The following example generates a PDF file with the given text in the code. The file can be downloaded or previewed as needed.

PHP




<?php
    
ob_end_clean();
require('fpdf/fpdf.php');
  
// Instantiate and use the FPDF class 
$pdf = new FPDF();
  
//Add a new page
$pdf->AddPage();
  
// Set the font for the text
$pdf->SetFont('Arial', 'B', 18);
  
// Prints a cell with given text 
$pdf->Cell(60,20,'Hello neveropen!');
  
// return the generated output
$pdf->Output();
  
?>


 

Output:

Example 2: The following example helps in understanding the setting of the page header and footer along with printing many lines on different pages of PDF files.

PHP




<?php
  
require('fpdf/fpdf.php');
  
class PDF extends FPDF {
  
    // Page header
    function Header() {
          
        // Add logo to page
        $this->Image('gfg1.png',10,8,33);
          
        // Set font family to Arial bold 
        $this->SetFont('Arial','B',20);
          
        // Move to the right
        $this->Cell(80);
          
        // Header
        $this->Cell(50,10,'Heading',1,0,'C');
          
        // Line break
        $this->Ln(20);
    }
  
    // Page footer
    function Footer() {
          
        // Position at 1.5 cm from bottom
        $this->SetY(-15);
          
        // Arial italic 8
        $this->SetFont('Arial','I',8);
          
        // Page number
        $this->Cell(0,10,'Page '
            $this->PageNo() . '/{nb}',0,0,'C');
    }
}
  
// Instantiation of FPDF class
$pdf = new PDF();
  
// Define alias for number of pages
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',14);
  
for($i = 1; $i <= 30; $i++)
    $pdf->Cell(0, 10, 'line number ' 
            . $i, 0, 1);
$pdf->Output();
  
?>


Output:

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments