Search code examples
laravelfpdf

Trying to implement FPDF with all forms of instantiation but only one form works. Others give Error


Installed crabbley/fpdf-laravel as per instructions. Tried some sample code as follows:

$pdf= app('FPDF');
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Swordsmen Class Times');
$pdf->Output();

While the instantiation of fpdf is different from the samples in the tutorials, all works as expected and the pdf is displayed in the browser. I got this working sample from the crabbley packagist.org/packages/crabbly/fpdf-laravel readme under 'usage'. The 'usage' instructions also provide an alternative instantiation viz: $pdf = new Crabbly\FPDF\FPDF; The tutorial samples use something slightly different again, ie

require('fpdf.php');
x=new FPDF();

and thus are a little different. When I changed it to be the same as the tutorial, all I changed was the instantiation line from

$pdf= app('FPDF');

to

$pdf = new FPDF('L', 'mm','A4');

and I get the error 'Class 'App\Http\Controllers\FPDF' not found'. I do not understand the difference between the different forms of instantiation and not sure what is going on but I need the latter format so I can set page orientation etc. I also tried the usage format as described above with the same sort of error, ie new Crabbly\FPDF\FPDF not found. I have tried the require statement but FPDF is not found and I am unsure where to point 'require' to.

Installation consisted of: composer require crabbly/fpdf-laravel add Crabbly\FPDF\FpdfServiceProvider::class to config/app.php in the providers section

Any suggestions will be appreciated.


Solution

  • You are using an implementation for the Laravel framework that binds an instance of FPDF to the service container. Using app('FPDF') returns you a new instance of FPDF, which is pretty much the same what new FPDF() would do.

    The require way of using it is framework agnostic and would be the way to use FPDF if you are just using a plain PHP script. While you could use this way with Laravel too, why would you want to do that?

    The reason the require does not work, by the way, is that the fpdf.php file is not found from where you call it. It would be required to sit in the same directory unless you give it a path. Considering you installed it using composer, the fpdf.php script, if any, should sit inside the vendor directory.

    However, just go with using the service container. The line $pdf = new FPDF('L', 'mm','A4'); just creates a new instance of the FPDF class and initializes it by passing arguments to the constructor, these being 'L' for landscape orientation, 'mm' for the measurement unit, and 'A4' for the page size. Without knowing the package you use and having testing it, you should also be able to set them equivalently by calling:

    $pdf = app('FPDF', ['L', 'mm', 'A4']);
    

    Hope that helps!