Welcome to our comprehensive guide on using the FPDF library to set fonts in PHP! In this tutorial, we'll explore how to control the font style, size, and family in your PDF documents, making them visually appealing and easy to read. Let's dive right in! π―
Before we begin, make sure you have FPDF library installed. If not, you can download it from here and follow the installation instructions.
First, let's create a new PDF document:
require('fpdf.php');
$pdf = new FPDF();Setting the font family is straightforward. You can choose from the predefined fonts provided by FPDF such as Arial, Courier, Times, and many more:
// Set the font to Arial
$pdf->SetFont('Arial');π Note: You can find the complete list of available fonts in the FPDF documentation.
Next, let's set the font size. We can use various font sizes like 8, 10, 12, etc., depending on our needs:
// Set the font size to 12
$pdf->SetFontSize(12);You can combine font family and size to achieve the desired look:
// Set the font to Arial, size 12
$pdf->SetFont('Arial', '', 12);π‘ Pro Tip: If you want bold text, use 'B' instead of ''. For italics, use 'I'. For bold and italics, use both 'B' and 'I'.
To set the font style, use the SetTextColor() function along with the SetFont() function:
// Set the font to Arial, size 12, bold and red
$pdf->SetTextColor(255, 0, 0); // RGB for red
$pdf->SetFont('Arial', 'B', 12);You can adjust the font weight using the SetFont() function with the following parameters:
'B' for bold'I' for italic'BI' for bold and italic'U' for underline'UI' for underline and italic'UO' for underline and bold'UIO' for underline, bold, and italicFor example, to create bold and underlined text, use:
$pdf->SetFont('Arial', 'BU', 12);Now that we've covered the basics, let's put it all together and create a simple PDF document with various font styles:
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
// Regular text
$pdf->SetFont('Arial', '', 12);
$pdf->Cell(0, 10, 'Regular text', 0, 1, 'L');
// Bold text
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 10, 'Bold text', 0, 1, 'L');
// Italic text
$pdf->SetFont('Arial', 'I', 12);
$pdf->Cell(0, 10, 'Italic text', 0, 1, 'L');
// Bold and italic text
$pdf->SetFont('Arial', 'BI', 12);
$pdf->Cell(0, 10, 'Bold and italic text', 0, 1, 'L');
// Underlined text
$pdf->SetTextColor(0, 0, 255); // Underline color: blue
$pdf->SetFont('Arial', 'U', 12);
$pdf->Cell(0, 10, 'Underlined text', 0, 1, 'L');
// Save the PDF
$pdf->Output();Which function is used to set the font family in FPDF?
That's it for today! In our next lesson, we'll delve deeper into FPDF and explore more features to make your PDF documents even more exciting. Stay tuned! π Note: Practice is key, so don't forget to experiment with the code examples provided! β
Happy coding! π»π»π»