Saturday, 3 December 2011

How to write PDF file in PHP?

PHP is a dynamic web development language with some surprising capabilities. It can even create PDF documents on the fly, if right third party library is available. Here in this post we are using FPDF library. You can download the same from here. Following is the example how you can write a simple pdf file using this library:



    //Connection to the database
    $link = mysql_connect("localhost","root","");
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    //end of database connection code


    $pdf=new FPDF();


    $pdf->Cell(50,3,"Learn how to write PDF Files in PHP");

    $text = "As a PHP programmer on any day you may need to write PDF file using PHP at run time. Here i have just tried to include each and everything required to write pdf file. Please go through the following blog link.";
     /* While you are using text we would recommend to use this function only because This method prints text from the current position. When the right margin is reached (or the \n character is met) a line break occurs and text continues from the left margin. Upon method exit, the current position is left just at the end of the text. */


    $link = "";
    $pdf->SetTextColor(0,136,60); //set color of the text using R,G,B combination

    $pdf->Cell(10,5,"User Id");

    //Get data from table.
    $result=mysql_query("select * from users order by user_id");
    $pdf->Image('images/php.jpg', 50, 50, 55, 35, 'JPG'); // inserts the image
    $pdf->Output("shiv.pdf","F"); // It would automatically call $pdf->Close();


Download the library and check more commands you can use to create an effective pdf as per the requirements.

Thanks!!!!!!!!!! Enjoy Programming :)

1 comment:

  1. Hi. This service here allows you to easily edit your PDF documents.

    You can fill out PDF form, save it, fax it, and email it.


Thanks for your valuable comments.