How to generate PDF file using PHP ?
Last Updated :
02 Jul, 2021
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' );
$pdf = new FPDF();
$pdf ->AddPage();
$pdf ->SetFont( 'Arial' , 'B' , 18);
$pdf ->Cell(60,20, 'Hello GeeksforGeeks!' );
$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 {
function Header() {
$this ->Image( 'gfg1.png' ,10,8,33);
$this ->SetFont( 'Arial' , 'B' ,20);
$this ->Cell(80);
$this ->Cell(50,10, 'Heading' ,1,0, 'C' );
$this ->Ln(20);
}
function Footer() {
$this ->SetY(-15);
$this ->SetFont( 'Arial' , 'I' ,8);
$this ->Cell(0,10, 'Page ' .
$this ->PageNo() . '/{nb}' ,0,0, 'C' );
}
}
$pdf = new PDF();
$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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...