Jump to content
Larry Ullman's Book Forums

Making My Own Pdf Invoices


Recommended Posts

Hi there everyone. In this book Larry uses PayPal as a payment solution. I have different needs as my site will not work with a payment service.

 

I want to output MYSQL data onto a PDF using the FPDF Library. I have looked around on the web and can't seem to find a understandable solution. Will somebody please help me with this? This solution below works perfectly with a text file, but I want a user to retrieve their monthly invoice by the click of a button. The .txt source must thus be substituted with MYSQL data. The problem is when I query MYSQL as usual, it gives the following error: FPDF error: Some data has already been output, can't send PDF file.

 

Can anybody over here please help me with a workable solution?

 

Thank you in advance!

 

 

My Code is as follows:

 

My Current data load function which usually takes a .txt file as parameter:

 

function LoadData($file)

{

 

$lines = file($file);

$data = array();

foreach($lines as $line)

$data[] = explode(';',trim($line));

return $data;

}

This is a piece of my fpdf.php library which creates the columns:

function ImprovedTable($header, $data)

{

 

$this->Ln(15);

$this->SetFontSize(11);

$w = array(20, 90, 20, 12, 50);

// Header

for($i=0;$i<count($header);$i++)

$this->Cell($w[$i],7,$header[$i],1,0,'C');

$this->Ln();

// Data

 

foreach($data as $row)

{

$this->SetFontSize(9);

$this->Cell($w[0],9,$row[0],'LR',0,'C');

$this->Cell($w[1],9,$row[1],'LR',0,'C');

$this->Cell($w[2],9,$row[2],'LR',0,'C');

$this->Cell($w[3],9,$row[3],'LR',0,'C');

$this->Cell($w[4],9,$row[4],'LR',0,'C');

$this->Ln();

}

// Closing line

$this->Cell(array_sum($w),0,'','T');

}

This is where the PDF is created. Here I'm still using the text file to get my data but want to use data from my table:

$pdf=new PDF();

// Column headings

$header = array('Ref #', 'Headline', 'Cost', 'Month', 'Date of transaction');

// Data loading

$data = $pdf->LoadData('invoice.txt');

$pdf->SetFont('Arial','',14);

$pdf->AddPage();

$pdf->ImprovedTable($header,$data);

$pdf->Output();

This is the SQL Query that I tried to include in my PDF creater. The database connection is also include I have not added it here however, so that is not the problem.

$query_database = "SELECT * FROM invoices WHERE user_number = '10'";

 

$connected_query = mysqli_query($connect_to_database, $query_database);

 

while ($result = mysqli_fetch_array($connected_query)) {

$invoice_data[] = $result;

}

 

foreach($invoice_data as $data);

Link to comment
Share on other sites

I, too, had problems incorporating a MySQL query in the same script as the FPDF code, so what I do is query the database and retrieve all the information on the page that has the button or link that creates the PDF into either hidden form elements, and POST that information to the FPDF page, or into $_SESSION variables and redirect to the FPDF page. If you spent a long time working at it, you could probably modify the FPDF code so you could do it all in once script, but I found it easier to make it a two-step process. The $_SESSION route would be more secure, since you wouldn't be transmitting any of the invoice information.

  • Upvote 1
Link to comment
Share on other sites

Hi there Paul.

 

I have tried your solution using $_SESSION. I'm still relatively new to PHP especially OOP as used here. I can't get it to work. It tells me that _SESSION is a undefined variable. I have stored all the info in a SESSION on the page with the link to my invoice. A var_dump of the SESSION varible confirms that the session does contain the data. I am however not too sure as to where and how I have to adjust the above code to include this data. The data is stored in a multidimensional array form. In other words, the $_SESSION['invoice_data'] is an array with for ex. 3 array values(which contains the data that I want to insert into my invoice). I have tried removing the loaddata function and adding another foreach into my improvedtable function, running this loop for my $_SESSION['invoice_data'] array. It is here however that it gives me the _SESSION undefined variable error.

 

Could you please give me some advice as to how you achieved success? I have really met my match with this script!!

Link to comment
Share on other sites

Did you add session_start() to the page that includes the FPDF library? You should add that and do any variable validation/manipulation before you load the FPDF library. I haven't used session variables, but it should work. I have used POST data, and I do my validation and variable assignments before I include the FPDF library. My script looks something like this (shortened, but you should get the idea):

// FORM VALIDATION
if (isset ($_POST['submitted'])) {

   // instName
   if (!empty ($_POST['instName'])) {
    $institutionName = $_POST['instName'];
   } else {
    $institutionName = FALSE;
    $msg .= '<p>Please enter your Institution Name.</p>';
    echo '<script type="text/javascript" language="javascript">missingFieldIds.push("instName");</script>';
   }

   // channel
   if (!empty ($_POST['channel']) && $_POST['channel'] != '0') {
    $deliveryChannel = $_POST['channel'];
   } else {
    $deliveryChannel = FALSE;
    $msg .= '<p>Please select a Delivery Channel.</p>';
    echo '<script type="text/javascript" language="javascript">missingFieldIds.push("channel");</script>';
   }

   // create pdf if required fields completed
   if ($institutionName && $deliveryChannel) {
    // required fields available, load FPDF library
    require ($_SERVER['DOCUMENT_ROOT'] . '/fpdf/fpdf.php');

    // generate filename
    $filename = 'Training_Attendees_' . time () . '.pdf';

    // build pdf
    $pdf=new FPDF('P', 'pt', "Letter");

    $pdf->SetMargins(18,96,18);
    $pdf->SetFillColor(114,187,57);
    $pdf->AddPage();
    $pdf->Image($_SERVER['DOCUMENT_ROOT'] . '/images/TrainingServicesWhite.png', 12, 12, 315, 41, 'png');
    //$pdf->Ln();
    $pdf->Ln();
    $pdf->Ln();
    $pdf->SetFont('Arial', '');
    $pdf->SetFontSize(10);
    $pdf->Cell(100, 12, 'Institution Name:', 0, 0, 'R');
    $pdf->Cell(200, 12, "$institutionName", 0, 0, 'L');
    $pdf->Cell(100, 12, 'Delivery Channel:', 0, 0, 'R');
    $pdf->Cell(200, 12, "$deliveryChannel", 0, 0, 'L');
    $pdf->Cell(0, 16, '', 1, 1, 'L');
    $pdf->Image($_SERVER['DOCUMENT_ROOT'] . '/images/HarlandFooter600px.png', 5, 720, 600, 59, 'png');
    $pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/secure/trainer_uploads/' . $filename, 'F');
   }
}

The above code saves to a file on the server, but there are other methods of delivering the pdf. You'll probably want to have it open in their browser.

 

Hope this helps.

  • Upvote 1
Link to comment
Share on other sites

Hi Larry. Why isn't session included as usual by my config script? Is it because this PDF is opened in a new tab? This might be a stupid question so excuse me but I'm still a beginner. Once again thanks for your wonderful book. Would love one about OOP PHP!

Link to comment
Share on other sites

I will most certainly buy it after my current project is finished. I want to develop my current project even further and make it simpler as it's quite messy right now, but it works and I've learned lots via the development of it. Hopefully I'll find your lessons on OOP just as easy to understand!

Link to comment
Share on other sites

 Share

×
×
  • Create New...