The Fpdi Class Initiate and use the Fpdi class

Introduction

The FPDI class is an extension for FPDF allowing you to import existing PDF pages into FPDF. The class offers all available methods as you already know from FPDF and extends it with some more methods.

Usage

The usage of FPDI follows a simply logic:

  1. Define the document to take pages from.
  2. Import an existing page of the document
  3. Use the imported page on a page created with FPDF

By this you will notice that you will not edit the original document but you will create a completely new document by import another one page by page.

Methods

Beside the methods of FPDF and FpdfTpl the class offers or overwrites following methods: 

getImportedPageSize()

Get the size of an imported page.

getTemplateSize()

Get the size of an imported page or template.

importPage()

Imports a page.

setSourceFile()

Set the source PDF file.

useImportedPage()

Draws an imported page onto the page.

useTemplate()

Draws an imported page or a template onto the page or another template.

Read PDF Documents From Any Source

Internally FPDI makes use of a StreamReader class which uses low level functions, such as fread() or ftell(), to interact with the stream.

The stream reader class offers static methods to create instances by a specific input type. It's constructor allows you to pass any seekable open stream resource: 

__construct()

StreamReader constructor.

createByFile()

Creates a stream reader instance by a filename.

createByString()

Creates a stream reader instance by a string value.

With these you can use a PDF document from any source. 

The Fpdi::setSourceFile() method allows you to pass several types which will be evaluated internally to a StreamReader instance:

PHP
// use a resource
$fh = fopen('a/path/to/a.pdf', 'rb');
$pdf->setSourceFile(new StreamReader($fh));
// same as
$pdf->setSourceFile($fh);
// don't forget to call fclose($fh);

// use a path
$path = 'a/path/to/a.pdf';
$pdf->setSourceFile(StreamReader::createByFile($path));
// same as
$pdf->setSourceFile($path);

// use a string
$pdfString = '%%PDF-1.4...';
$pdf->setSourceFile(StreamReader::createByString($pdfString));