PHP MYSQL and PDFLIB  Reporting problems

Posted on 2009-05-15
Last Modified: 2013-12-12
I am trying now to create a report on PHP MYSQL using the PDFlib class. I am using as base one of the examples (the only one) I found to get something similar (invoice.php). I have got a blank page on my browser and a error on Adobe Acrobat (File does not begin with '%PDF-')
I find problems to find how to pass the information from a mysql query to a table on pdf
Any help will be really welcome. I am beginner.
Here is the PHP monster I created. What is wrong. My guess is the $data[] variable twice on the program....I am not able to draw a table to keep there the data
Many thanks

/*$Id: stareport.php, v 1.0 15/05/2009 rjs Exp $


*PDFlib client. stability report in PHP


$left = 55;

$right = 530;

$fontsize = 12;

$pagewidth = 595;

$pageheight = 842;

$infile = "c:/wamp/www/pdf/data/stationeryreport.pdf";

//Table in database has 9 fields

$baseopt =  "ruler        {   15 25  160 200 240 280  360   410    460} " .

			"tabalignment { right left right right right right right right right} " .

			"hortabmethod ruler fontsize 12 ";

/*this is where font/image/PDF input files live*/

$searchpath = "c:/wamp/www/stability/data/";

//this is the connection to mysql

require ('connectionRoot.php');

$queTbl = "SELECT id, item, wts, lcg, tcg, vcg, wts*lcg as LMMT, wts*tcg as TMMT, wts*vcg FROM lightship";

$res = mysql_query($queTbl, $conexion) or die(mysql_error());

$tot = mysql_num_rows($res);

//Database is numeric , it has only one column with string on the field {item} 

$ixx = 0;

while($datatmp = mysql_fetch_assoc($res)) {

$ixx = $ixx+1;

$data[] = array_merge($datatmp, array('num'=>$ixx));



    $p = new PDFlib();

        # This means we must check return values of load_font() etc.

    $p->set_parameter("errorpolicy", "return");

    /* Set the search path for fonts and PDF files */

    $p->set_parameter("SearchPath", $searchpath);

    /* This line is required to avoid problems on Japanese systems */

    $p->set_parameter("hypertextencoding", "winansi");

    /*  open new PDF file; insert a file name to create the PDF on disk */

    if ($p->begin_document("", "") == 0) {

	die("Error: " . $p->get_errmsg());


    $p->set_info("Creator", "pdfrepgenPDFlib.php");

    $p->set_info("Author", "Pedraz");

    $p->set_info("Title", "Create report from mySql sample (PHP)");

    $stationery = $p->open_pdi($infile, "", 0);

    if ($stationery == 0) {

    die("Error: " . $p->get_errmsg());



    $page = $p->open_pdi_page($stationery, 1, "");

    if ($page == 0){

    die("Error: " . $p->get_errmsg());



    $boldfont = $p->load_font("Helvetica-Bold", "winansi", "");

    if ($boldfont == 0){

    die("Error: " . $p->get_errmsg());



    $regularfont = $p->load_font("Helvetica", "winansi", "");

    if ($regularfont == 0){

    die("Error: " . $p->get_errmsg());


    $leading = $fontsize + 2;


    /*Establish coordinates with the origin in the upper left corner*/

    $p->begin_page_ext($pagewidth, $pageheight, 'topdown');  


    $p->fit_pdi_page($page, 0, $pageheight, "");



    $p->setfont($regularfont, $fontsize);


    /*print left note on the top*/

    $y = 140;


    $p->show_xy("1.- Lightship & Various", $left, $y);


    $p->setfont($regularfont, $fontsize - 4);

    $p->continue_text("(This is the report for lightship & various weights once the Moments have been calculated)");


    /* print the report header line (here they are the field names */

    $y = 180;

    $buf = sprintf("\tID\tItem\tWeigth\tLCG\tTCG\tVCG\tLMMT\tTMMT\tVMMT");

    $optlist = sprintf("%s font %d ", $baseopt, $boldfont);

    $textflow = $p->create_textflow($buf, $optlist);

    if ($textflow == 0){

    die("Error: " . $p->get_errmsg());


    $p->fit_textflow($textflow, $left, $y-$leading, $right, $y, "");


    $y += 2*$leading;

    $total = 0;

    $optlist = sprintf("%s font %d ", $baseopt, $regularfont);

 //I think the big problem is here......

    for ($i = 0; $i < count($data); $i++){

    //$sum = $data[$i]{"price"}*$data[$i]{"quantity"};

    $sum = $data[$i]{"wts"};

    $buf = sprintf("\t%d\t%s\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f", $i+1, $data[$i]{"id"},

	  $data[$i]{"item"}, $data[$i]{"wts"},$data[$i]{"lcg"},$data[$i]{"tcg"},$data[$i]{"vcg"},$data[$i]{"LMMT"},$data[$i]{"TMMT"},$data[$i]{"VMMT"});

    $textflow = $p->create_textflow($buf, $optlist);

    if ($textflow == 0){

	  die("Error: " . $p->get_errmsg());


    $p->fit_textflow($textflow, $left, $y-$leading, $right, $y, "");


//$sum is the sum of the field {"wts"}

    $y += $leading;

    $total +=$sum;


    $y += $leading;

    $p->setfont($boldfont, $fontsize);

    $p->fit_textline(sprintf("%.2f",$total), $right, $y, "position {100 0}");





    $buf = $p->get_buffer();

    $len = strlen($buf);

    header("Content-type: application/pdf");

    header("Content-Length: $len");

    header("Content-Disposition: inline; filename=pdfrepgenPDFlib.pdf");

    print $buf;


catch (PDFlibException $e) {

    die("PDFlib exception occurred in invoice sample:\n" .

	"[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " .

	$e->get_errmsg() . "\n");


catch (Exception $e) {



$p = 0;


Open in new window

Question by:Pedraz
  • 2
LVL 108

Accepted Solution

Ray Paseur earned 500 total points
ID: 24403802
I cannot really understand the logic in the code posted here, but I can offer some ideas that may be helpful.  

If you have not looked at it, learn about FPDF.  Google it - open source and very easy to use.

When you are dealing with data-dependent programing, or just curious about what your variables contain, you can use var_dump() to print out a variable.  The variable can be anything - an item, an array, an object, etc.  I find it is useful to echo "<pre>"; before var_dump(); so I can get an easily readable printout.

You might want to use var_dump($p); near line 113 just to see what is going on there.

Another thing that would be helpful is to add this to the top of the script, so you can see any assumptions that PHP is making.

Finally if you indent the code like in the code snippet, you will find that it becomes easy to read and follow the conditional structures.  Note that the curly braces always line up and are on their own lines.

HTH, and good luck with it, ~Ray


$a = 2


if ($a == 2)


    echo "A IS TWO";

} else



    if ($a == 3)


        echo "A WAS TWO";




Open in new window


Author Closing Comment

ID: 31581960
You are right. I am using FPDF now and I completed the reporting for my website. Thanks for the tip
LVL 108

Expert Comment

by:Ray Paseur
ID: 24406810
Great!  Thanks for the points.  I'm glad FPDF is working for you.  I have found it to be very useful.  Best, ~Ray

Featured Post

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Earlier I wrote an article about the new lookup functions ( that ship with SQL Server 2008 R2.  In this article I’m going to show you another new feature of SSRS 2008 R2, this time in the vis…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

947 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now