PDF view in browser and export as file – PHP

We are going to use the library named FPDF you can download it from it’s official site. You will get ZIP file in your download, extract it and you will get just 1 folder. You need to copy that folder in your project root folder where it can be accessible. In that folder you will also find a folder named “font” that will be used if you want to add more fonts in your PDF file. By default it came up with 14 fonts at the time of writing this. So we are going to create a simple invoice page which is a common example in E-commerce sites where once you buy any product then an invoice has been generated which contains all the order details. It typically contains company logo, buyer name & address, all products which were added in cart and their quantity & price. Lastly it has total sum of all products, some also have shipping cost so they display grand total which is the sum of all products price and the shipping cost.

In order to create PDF view in your browser you first needs to include the fpdf.php inside your downloaded folder. Then you need to create an instance of FPDF class, we will be using this object throughout this tutorial. Then needs to add a page in pdf otherwise it will throw an exception that no page has been found in PDF. Lastly you will render the PDF in browser by calling the output() function with your PDF instance. We will be using index.php to display the PDF file but you might be creating a separate file for viewing PDF. Paste the following code in your index.php file:

<?php

// Include the PDF class
require_once "fpdf181/fpdf.php";

// Create instance of PDF class
$pdf = new FPDF();

// Add 1 page in your PDF
$pdf->AddPage();

// Render the PDF in your browser
$pdf->output();

?>

Create header

Header will contain an image which can be served as a logo on top left and on right you can either display the name of company or the subject of report. Example of subject of report can be “report”, “invoice”, “letter” etc. In order to insert image in your PDF file you need to call the Image(src, x, y, width, height) function where src will be the source of image which needs to be placed, typically we place company logo in PDF. X & Y are the co-ordinates where image will be placed and width & height are self-explanatory I believe. Paste the following code after AddPage() function and before the output() function:

<?php

// Place image on top left with 100px width
$pdf->Image("logo.jpg", 10, 10, 100);

// Set Arial Bold font with size 22px
$pdf->SetFont("Arial", "B", 22);

// Give margin from left
$pdf->SetX(160);

// Write text "Invoice" with 0 width & height (it will still be visible)
$pdf->Cell(0, 0, "Invoice");

// Move the cursor to next line
$pdf->Ln();

?>

Output

Display database data in PDF

Suppose some customer have purchased something from your website and you have saved his selected products in your database, now you need to show these values from database inside the PDF. We are going to show the database data in table format. We will be using Cell() function with PDF instance and it’s parameters are: Cell(x, y, text, border, ln, alignment, fill). It’s explanation is given below. First we are going to create a header for table which will be highlighted from other rows of the table:

XMargin from left
YMargin from top
textText which needs to be displayed
borderBorder around the text (1 means 1px)
lnWhere should next cell starts (0 means to right, 1 means next line)
AlignmentAlignment of text (can be “L” for left, “R” for right, “C” for center and “J” for justify)
FillWhether this cell nexts to be filled or not (true / false)
<?php

// Sets the background color to light gray
$pdf->SetFillColor(209, 207, 207);

// Cell
$pdf->Cell(50, 10, "Product Code", 1, 0, "L", true);
$pdf->Cell(50, 10, "Quantity", 1, 0, "L", true);
$pdf->Cell(50, 10, "Price", 1, 0, "L", true);
$pdf->Ln();

?>

Output

Now we will run the query on database and display all returned records in table rows. But first we need to make the font from bold to normal because bold only looks good for headings.

<?php

// Setting the font to Arial normal with size 16px
$pdf->SetFont("Arial", "", 16);

// Connecting with database
$conn = mysqli_connect("localhost", "root", "", "classicmodels");

// Getting records from database
$result = mysqli_query($conn, "SELECT * FROM orderDetails WHERE orderNumber = '10101'");

// Iterate through each record
while ($row = mysqli_fetch_object($result))
{
	// Create cells with 50px width, 10px height and 1px border
	$pdf->Cell(50, 10, $row->productCode, 1);
	$pdf->Cell(50, 10, $row->quantityOrdered, 1);
	$pdf->Cell(50, 10, $row->priceEach, 1);

	// Moving cursor to next row
	$pdf->Ln();
}

?>

Output

In these type of cases you may also wanted to show the total of all products which includes the sum of all products unit price multiplied by quantity. Also you also want to add the shipping cost if the product needs to be delivered physically. So first we will add all the product’s price in a variable and then we will add the shipping cost in it. Then we will display 3 sections, 1 for product’s total price, 1 for shipping cost and 1 for grand total which will be sum of total price and shipping cost. We are going to highlight the grand total section too because it is the final price and it needs to get attention:

<?php

$total = 0;
while ($row = mysqli_fetch_object($result))
{
	// ..... display cells here

	$total += $row->priceEach * $row->quantityOrdered;
}

$pdf->Ln();
$pdf->SetX(60);
$pdf->Cell(50, 10, "Total", 1);
$pdf->Cell(50, 10, "$" . $total, 1);
$pdf->Ln();

$pdf->SetX(60);
$pdf->Cell(50, 10, "Shipping", 1);
$pdf->Cell(50, 10, "$9", 1);
$pdf->Ln();

$pdf->SetX(60);
$pdf->Cell(50, 10, "Grand Total", 1, 0, "L", true);
$pdf->Cell(50, 10, "$" . ($total + 9), 1, 0, "L", true);
$pdf->Ln();

?>

Output

Downloading the PDF

To download the PDF as external file or exporting the file in your computer, you need to do few steps. First you need to change your output() function and make it to accept two arguments, first will be the name of file that will be save in your server and second will be the character F which indicates that user wants to create a file and instead of displaying in browser. Then you need to pass some headers which will download the file, and finally you can remove the file from server if you want. Because in some cases you just want the file to get downloaded by user and not to keep in your server.

<?php

// Creates a file in server
$pdf->output("Invoice.pdf", "F");

// Tell that the file will be PDF
header("Content-type: application/pdf");

// Set the file as attachment and set its name to "Invoice.pdf"
header("Content-disposition: attachment; filename = Invoice.pdf");

// Read the source file (which needs to be downloaded)
readFile("Invoice.pdf");

// Delete the file from server
unlink("Invoice.pdf");

?>

That’s it. If you face any problem in following this tutorial, please feel free to ask in the comments section below.



Leave a Reply

Please disable your adblocker or whitelist this site!