php-fakerHow can I generate a PDF using PHP Faker?
Generating a PDF using PHP Faker is quite simple. The following code snippet shows how to generate a PDF containing a list of random names using PHP Faker:
<?php
require_once 'vendor/autoload.php';
$faker = Faker\Factory::create();
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Random Names');
$pdf->Ln();
foreach ($faker->words as $name) {
$pdf->Cell(40,10,$name);
$pdf->Ln();
}
$pdf->Output('random_names.pdf','F');
This code creates a PDF file named random_names.pdf
containing a list of random names. The require_once
statement loads the Faker library. The Faker\Factory::create()
statement creates a Faker instance. The FPDF
class is used to create a PDF document. The AddPage()
method adds a new page to the document. The SetFont()
method sets the font type, style, and size. The Cell()
method is used to add a cell containing the list title. The Ln()
method adds a new line. The foreach
loop iterates through the words
property of the Faker instance and adds each name to the document. Finally, the Output()
method saves the document to a file.
Parts of the code:
require_once 'vendor/autoload.php';
- this statement loads the Faker library.$faker = Faker\Factory::create();
- this statement creates a Faker instance.$pdf = new FPDF();
- this statement creates a PDF document.$pdf->AddPage();
- this statement adds a new page to the document.$pdf->SetFont('Arial','B',16);
- this statement sets the font type, style, and size.$pdf->Cell(40,10,'Random Names');
- this statement adds a cell containing the list title.$pdf->Ln();
- this statement adds a new line.foreach ($faker->words as $name) {
- this loop iterates through thewords
property of the Faker instance.$pdf->Cell(40,10,$name);
- this statement adds each name to the document.$pdf->Output('random_names.pdf','F');
- this statement saves the document to a file.
Helpful links
More of Php Faker
- How do I generate a fake year in Laravel using Faker?
- How do I generate a zip file using PHP Faker?
- How do I use PHP Faker to generate XML data?
- How can I specify a string length when using PHP Faker?
- How do I generate a random number using PHP Faker?
- How can I use PHP Faker in a Symfony project?
- How do I generate a random digit using PHP Faker?
- How can I use Faker in PHP to generate fake data?
- How can I generate a unique ID using PHP Faker?
- How can I generate a fake URL using PHP Faker?
See more codes...