go top

MEGA Sale

  • Colection of 65 PHP scripts for $4.29 each

Get 65 PHP scripts in a bundle for $4.29 each!

View Offer

Create PDF file with PHP

Tuesday, 6th December, 2011  /  PHP Tutorials  /  30 Comments
PDFs have become widespread enough among businesses and institutions to make automatically and dynamically producing them in large quantity is a valuable skill to learn. Portable Document Files from Adobe are easily produced in PHP, making it an even better glue language than before. Since anyone can install PHP, they can use the simple PHP 5 class of PDFlib that's provided to make a as many PDFs in whatever format you need.

The irony is, of course, PDFlib is now commercial and offers a PDFlib Lite. Either way, the PDFlib library has an unwieldy learning curve, and instead, I recommend FPDF for your general PDF usages. This is a freeware PDF library written completely in PHP, so no PECL or PEAR installation is required, which does slow it down. So, a large business shouldn't use this to process hundreds of PDFs, but for smaller jobs it works.

Making a basic PDF document on the fly

I'll show you how to make a basic PDF document with text blocks of different alignments, as well as double-spacing, headers and footers and displaying an image.

Let's jump immediately into an example showing all of this:

<?php
require('classes/fpdf/fpdf.php');
class PDF extends FPDF {

function Header() {
$this->SetFont('Times','',12);
$this->SetY(0.25);
$this->Cell(0, .25, "John Doe ".$this->PageNo(), 'T', 2, "R");
//reset Y
$this->SetY(1);
}

function Footer() {
//This is the footer; it's repeated on each page.
//enter filename: phpjabber logo, x position: (page width/2)-half the picture size,
//y position: rough estimate, width, height, filetype, link: click it!
$this->Image("logo.jpg", (8.5/2)-1.5, 9.8, 3, 1, "JPG", "https://www.phpjabbers.com");
}

}

//class instantiation
$pdf=new PDF("P","in","Letter");

$pdf->SetMargins(1,1,1);

$pdf->AddPage();
$pdf->SetFont('Times','',12);

$lipsum1="Lorem ipsum dolor sit amet, nam aliquam dolore est, est in eget.";

$lipsum2="Nibh lectus, pede fusce ullamcorper vel porttitor.";

$lipsum3 ="Duis maecenas et curabitur, felis dolor.";

$pdf->SetFillColor(240, 100, 100);
$pdf->SetFont('Times','BU',12);

//Cell(float w[,float h[,string txt[,mixed border[,
//int ln[,string align[,boolean fill[,mixed link]]]]]]])
$pdf->Cell(0, .25, "lipsum", 1, 2, "C", 1);

$pdf->SetFont('Times','',12);
//MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
$pdf->MultiCell(0, 0.5, $lipsum1, 'LR', "L");
$pdf->MultiCell(0, 0.25, $lipsum2, 1, "R");
$pdf->MultiCell(0, 0.15, $lipsum3, 'B', "J");

$pdf->AddPage();
$pdf->Write(0.5, $lipsum1.$lipsum2.$lipsum3);

$pdf->Output();
?>


I create a PDF in Portrait mode with a Letter size and measured in inches. Then, I set the margins to 1 inch, add our first page, and then set the Font to Times, Size 12. Then, my 3 dummy texts, and after that I set the fill color that will be the space behind my title's text with a bold/underlined modifier. After that, I print the title, then reset the font and specify some different types of MultiCells. The page is made up of cells on an x,y plane in FPDF, which makes it pretty convenient to work with for basic PDF editing.

The headers and footers are functions automatically called in the parent class, but they do nothing by default. That means we have to redefine them to our needs. In this case, a name and page number as the header and a logo with a link as the footer. These are repeated on each page.

Note that in order to place the text in the proper location, I had to use the SetX and SetY functions. Don't forget to reset them to their normal flow when you're done in the header or footer, though!

Cells are individual units on the page. It is convenient to define a line with a single cell, but at the same time this can be achieved much more quickly by use of the MultiCell function which will automatically create a new cell as text is passed through. Write is just streamed text.

One thing to absolutely keep in mind is that you can't output any text to the browser when trying to send this PDF to the browser, if you're making it on the fly. If you're making it for storage or later use, then there's no problem outputting text to the user as well. This is accomplished by setting the parameters to Output appropriately.

The spacing is done with the line height. You have to do some math to figure out what you want. The line height is the entire height of the line, which means the lines are up against each other. That means whatever you set for the line height is spacing between the letters, as well!

With these skills in mind, you should be able to do whatever you want to a PDF. For even more functionality, there is a Scripts section, but of course there is always the PDFlib library which provides all kinds of specialization. FPDF is a highly documented library though, and it's really simple to use. Good luck!
Share on:

30 Comments to "Create PDF file with PHP"

befiv

befiv / July 24, 2015 at 18:16 pm

Hi...great tutorial!
I have been having trouble printing all the data from my table...I can only print the last row from it and I have been stressed with trying to use increment but I keep failing. I'm a novice developer and debugging is not one of my qualities...please help me increment and print all the rows from my table?! this is the code that is only printing the last row, I removed all the code I tried to implement the increment with since it was not working...


<?php
//require_once '../includes/dbconnect.php';
require_once ("file:///C:/xampp/htdocs/dompdf/dompdf_config.inc.php");
spl_autoload_register('DOMPDF_autoload');

$db_hostname= "localhost";
$db_username= "root";
$db_password= "";
$db_database= "project2";

//Connect to server.
$link = mysqli_connect($db_hostname, $db_username, $db_password);
if (!$link) {
die('Not connected : ' . mysqli_error());
}

//check for connection errors

if(mysqli_connect_errno()) {
//echo "Error: Could not connect to database.";
exit;
}

//Select the database.
$db_selected = mysqli_select_db($link, $db_database);
if (!$db_selected) {
die ('Cant use database : ' . mysqli_error());
}

$query="SELECT * FROM users WHERE admin='0'";
$result=mysqli_query($link,$query);

while($row = mysqli_fetch_assoc($result))
{

$fullnames= $row["fullnames"];
$username= $row["username"];
$email= $row["email"];
$mobile_no= $row["mobile_no"];
$usertype= $row["usertype"];

?>
<?php
$paper= "letter";
$orientation= "portrait";
$html= '<!doctype html>
<html>
<body>
<center><u>Registered Users List</u></center><br><br>
<ul data-role="listview">
<li>Fullnames: <b>'.$fullnames.'</b></li>
<li>Username: <b>'.$username.'</b></li>
<li>Email: <b>'.$email.'</b></li>
<li>Mobile No: <b>'.$mobile_no.'</b></li>
<li>Usertype: <b>'.$usertype.'</b></li>
<hr><br>
</ul>
</body></html>';
}
?>
<?php

ob_start();
$dompdf = new DOMPDF();
$dompdf->set_paper($paper, $orientation);
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("my_pdf.pdf", array("Attachment" => 0));
//$pdf = $dompdf->output();
//file_put_contents("saved_pdf.pdf", $pdf);
ob_end_flush();
exit(0);
//mysqli_close($link);
?>

tukkar

tukkar / July 13, 2015 at 07:23 am

Good tutorial

admin

admin / April 22, 2015 at 06:33 am

Looks like awesome not yet tested on my code

Harshil

Harshil / January 7, 2015 at 16:03 pm

Thnxxx...
PhP Jabbers And M. Ghoshal .

akash soni

akash soni / September 3, 2014 at 15:44 pm

could any one tell me where to put my php file name in the code..thank you in advance

deepa

deepa / November 21, 2013 at 09:15 am

where cani find classes/fpdf/fpdf.php file

M. Ghoshal

M. Ghoshal / February 5, 2014 at 05:04 am

You can give a file search for fpdf.php and you will be able to find the location. E.g., in my system it is in the folder: C:xamppphppearfpdffpdf.php. Hope this helps.

Hillybilly

Hillybilly / September 17, 2013 at 11:08 am

Huge. Tremendous. Thanks

David

David / June 20, 2013 at 04:47 am

I am using a database on my website and I was curious if there is a good way to call information from the database to put in the PDF?

If I am calling it on a general php page and the user is logged in, I can just add; <code><?php
if($form->value("fname") == ""){
echo $session->userinfo['fname'];
}else{
echo $form->value("fname");
}
?></code>

With this script (using the first tutorial), it just wants simple text in between ' ' (it shows 'Hello World' in the tutorial). If I put that code there, it completely destroys the structure.

komal

komal / April 11, 2013 at 12:39 pm

interesting.. going to use it for my website.

fervendra

fervendra / April 5, 2013 at 14:50 pm

great code...

Add your comment

Captcha

    Please, be polite and helpful and do not spam or offend others! We promise you will be treated the same way!

    Log in to your account to post your comments. If you still haven't joined our community yet, you can create your FREE account now!

    Posting tip:
    If you use code in your comments, please put it in these tags [php], [sql], [css], [js] PHP code example: [php] echo date("Y-m-d"); [/php]

    Thank you,
    PHPJabbers Team

    Free Scripts

    Add great new functionalities to your website with our Free Scripts collection.


    Free scripts

    PHP Scripts

    Check our extensive collection of top-notch PHP Scripts that will enhance your website!


    Commercial PHP scripts