Home » Create PDFs In PHP With Header/Footer

Add header with logo and footer in creating PDF files in PHP using FPDF Library Class. Position the data to your desired area, choose a font and display directly on a browser, or save to a LOCAL directory, or even force a file download of the generated PDF file.

Requirements:

  • Composer
  • PHP ^PHP 5.1
  • PHP Zlib
  • PHP GD

Step 1.

Setup dependencies.

{
    "require": {
        "setasign/fpdf": "^1.8"
    }
}

Step 2.

Install FPDF.

$ composer install

Step 3.

Create a new PHP file and name it create-pdf-files-with-header-footer-and-logo.php and copy/paste the codes below.

The objective is to create a basic PDF file with Header, Logo, and Footer, and display the generated PDF file on a browser.

<?php

// Load dependencies
require(__DIR__.'/vendor/setasign/fpdf/fpdf.php');

class PDF extends FPDF
{
    // Page header
    function Header()
    {
        // Logo
        $this->Image('images/ndriel-logo.png',10,6,30);
        // Arial bold 15
        $this->SetFont('Arial','B',15);
        // Move to the right
        $this->Cell(80);
        // Title
        $this->Cell(30,10,'My PDF Title',0,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');
    }
}

$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial','',12);
$pdf->Cell(40,10,'Hello World !');
$pdf->Output();

Result.

Header.

Footer.

Notes:

  • This tutorial is created with composer, but the dependency files can also be downloaded directly from the developers website (http://www.fpdf.org/).
  • Make sure the path to the dependency file (fpdf.php) is correct.
    // Load dependencies
    require(__DIR__.'/vendor/setasign/fpdf/fpdf.php');
  • To save the generated PDF file to a local directory, add the 'F' parameter and the path and name of the file to the Output().
    $pdf->Output('F', 'pdf-with-header-logo-and-footer.pdf');
    
  • To force a download of the generated PDF file, add the 'D' parameter and the path and name of the file the Output().
    $pdf->Output('D', 'pdf-with-header-logo-and-footer.pdf');
    

References:


Posted

in

by

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *