Jump to content
hardbouw

Convert PHP to PDF

Recommended Posts

I have been tasked to create an data entry and storage system for agents in a callcentre.

 

I have no prior PHP knowledge. I have with he help of various online tutorials gotten a thing in place  to insert data in to a mysql database and again display it in a table format.

 

Our financial provider is not happy with he csv format I am sending the data in to him, they need an separate application form in an form format for each client. I now have to get each sale the agents made, ie each record individually populate an HTML Template I created which then in turn have to be converted to pdf.

 

I searched around and none of the tutorials works for my situation, they all want to put all the data into an single table, I need each record in a separate table tried TCPDF, HTML2PDF and FPDF.

 

All those only work with plain html data, however my whole application is written in PHP.

 

This should be a simple fix for someone a bit more experienced in PHP.

 

Here is my CODE:

 

This works:

<?php
// server info
$server = 'localhost';
$user = 'root';
$pass = 'password';
$db = 'debtdb';




// connect to the database
$conn = new mysqli($server, $user, $pass, $db);


// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);


if(!isset($_POST['agentname'])) {
$search_sql="SELECT * FROM daily";
$search_query=mysqli_query($conn, $search_sql);
$search_rs=mysqli_fetch_assoc($search_query);
}


 if(!empty($search_query))  {


  while($search_rs = mysqli_fetch_array($search_query)) {

echo $search_rs["id"];
echo $search_rs["agentname"];
echo $search_rs["dateofsale"];
echo $search_rs["per_firstname"];
echo $search_rs["per_lastname"];
echo "<br>";

  }
}
?>

This however do not, HTML2PDF (I truncated everything to simplify matters):

 

<?php
// server info
$server = 'localhost';
$user = 'root';
$pass = 'password';
$db = 'debtdb';

// connect to the database
$conn = new mysqli($server, $user, $pass, $db);

// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);

if(!isset($_POST['agentname'])) {
$search_sql="SELECT * FROM daily";
$search_query=mysqli_query($conn, $search_sql);
$search_rs=mysqli_fetch_assoc($search_query);
}

 if(!empty($search_query))  {

  while($search_rs = mysqli_fetch_array($search_query)) {

    $content = "
<page>

echo $search_rs["id"];
echo $search_rs["agentname"];
echo $search_rs["dateofsale"];
echo $search_rs["per_firstname"];
echo $search_rs["per_lastname"];
echo "<br>";

</page>";

require_once(dirname(__FILE__).'/html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('P','A4','fr');
$html2pdf->WriteHTML($content);
$html2pdf->Output('exemple.pdf');  

  }
}
?>

TCPDF:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>


<h1>View Records</h1>




<?php
// connect to the database
include('connect-db.php');

 
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM clients ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{


// set table headers




//PDF Generating Start




// Include the main TCPDF library
<body>


<h1>View Records</h1>




<?php
// connect to the database
include('connect-db.php');


// get the records from the database
if ($result = $mysqli->query("SELECT * FROM clients ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{


//PDF Generating Start




// Include the main TCPDF library (search for installation path).
require_once('examples/tcpdf_include.php');
include('tcpdf.php');


// create new PDF document
$pdf = new TCPDF('L', PDF_UNIT, 'A4', true, 'UTF-8', false);


// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Asimegroup');
$pdf->SetTitle('Asime Loan App');
$pdf->SetSubject('Asime Loan Application Form');


// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);


// set margins
$pdf->SetMargins('5', '0', '0');




// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, '0');


// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);


// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'examples\lang\eng.php')) {
require_once(dirname(__FILE__).'examples\lang\eng.php');
$pdf->setLanguageArray($l);
}


// ---------------------------------------------------------


// set font
$pdf->SetFont('helvetica', '', 10);


// add a page
$pdf->AddPage();


$html = '
<body>
<br/>
<table>
  <tr>
    <td height="40px"></td>
  </tr>
  <tr>
    <td align="right" class="heading"  width="175px">Personal</td>
    <td align="left" class="heading" width="210px">Details:</td>
    <td width="10px"></td>
    <td align="right" class="heading" width="150px">Relative not</td>
    <td align="left" class="heading" width="170px">living with you:</td>
    <td width="10px"></td>
    <td align="right" class="heading" width="185px">Expenses:</td>
    <td width="100px"></td>
  </tr>
  <tr>
    <td class="subheading">SA Citizen?:</td>
    <td class="data"></td>
    <td></td>
    <td class="subheading">Name:</td>
    <td class="data"></td>
    <td></td>
    <td class="subheading">Bond / Rent:</td>
    <td class="data"></td>
  </tr>
  <tr> 
    <td class="subheading">Name:</td>
    <td class="data">' . $per_firstname . '</td>
    <td></td>
    <td class="subheading">Surname:</td>
    <td class="data">' . $per_lastname . '</td>
    <td></t d>
    <td class="subheading">Rates, Water, Electricity:</td>
    <td class="data"></td>
  </tr>


</table>';




// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');


// reset pointer to the last page
$pdf->lastPage();


// ---------------------------------------------------------


//Close and output PDF document
$pdf->Output('Asime_Loan'.$per_id.'.pdf', 'F');


//PDF Generating End


}


}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query


// close database connection
$mysqli->close();


?>

 

post-202103-0-28182500-1473072177_thumb.jpeg

Share this post


Link to post
Share on other sites

All those only work with plain html data, however my whole application is written in PHP.

Hold on a second. Are you saying that one of those works perfectly(ish) for you except for the fact that it needs "plain HTML data"? Because PHP is perfectly capable of generating said HTML data (even without displaying it), which could then be fed into one of those methods.

Share this post


Link to post
Share on other sites

I do not see anything in your attached image that could not be produced simply with FPDF.

Share this post


Link to post
Share on other sites
I have been tasked to create an data entry and storage system

 

I have no prior PHP knowledge.

Why in the world are they having someone with no experience build an application?

 

Our financial provider is not happy with he csv format I am sending the data in to him

 

That's because they know even less than you do. In that format you can pretty much end up with any output you want.  Since you have no experience, it is probably not something you should be attempting for use in a real business scenario. I could not PM you. I am available for hire.

Edited by benanamen

Share this post


Link to post
Share on other sites

This might be an issue with semantics but PHP only runs on the server and you want a PDF of data available on the client. The idea of PHP is it is capable of generating and outputting HTML to the client, or handing it off to any number of PDF generators in HTML format. PHP itself doesn't display anything, it generates HTML in order to accomplish this. So once you have the HTML generated with PHP (all those echo statements and table elements you have there), then you pass it into FPDF and FPDF will then generate your required PDF document which you can save somewhere on the server. I use DOMPDF but it's based on the same base code as MPDF and FPDF are. They're all essentially the same.

 

When I was first learning PHP, this took me over 6 months from start to finish to accomplish but now it's used every day.

Share this post


Link to post
Share on other sites

 PHP itself doesn't display anything, it generates HTML in order to accomplish this.

 

Really? Show me where the html is here: <?= 'Hello World' ?>

Edited by benanamen

Share this post


Link to post
Share on other sites

Really? Show me where the html is here: = 'Hello World' ?>

The HTML is

Hello World
It's not exactly valid HTML, but that's what the browser will interpret it as by automatically wrapping it in an and .

Share this post


Link to post
Share on other sites

The OP said PHP magically generates HTML which it does not.

Edited by benanamen

Share this post


Link to post
Share on other sites

If you are trying to interpret what he said literally then yes, you're right, PHP does not "magically" generate HTML.

 

However I think it's clear that what he meant was that PHP code must be used to create HTML - or any output, for that matter - and that it is not PHP by itself that is responsible for generating anything.

Share this post


Link to post
Share on other sites

This however do not, HTML2PDF (I truncated everything to simplify matters):

 

<?php
// server info
$server = 'localhost';
$user = 'root';
$pass = 'password';
$db = 'debtdb';

// connect to the database
$conn = new mysqli($server, $user, $pass, $db);

// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);

if(!isset($_POST['agentname'])) {
$search_sql="SELECT * FROM daily";
$search_query=mysqli_query($conn, $search_sql);
$search_rs=mysqli_fetch_assoc($search_query);
}

 if(!empty($search_query))  {

  while($search_rs = mysqli_fetch_array($search_query)) {

    $content = "
<page>

echo $search_rs["id"];
echo $search_rs["agentname"];
echo $search_rs["dateofsale"];
echo $search_rs["per_firstname"];
echo $search_rs["per_lastname"];
echo "<br>";

</page>";

require_once(dirname(__FILE__).'/html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('P','A4','fr');
$html2pdf->WriteHTML($content);
$html2pdf->Output('exemple.pdf');  

  }
}
?>

 

 

You should be using opposing quotes when nesting, try switching to an apostrophe ( ' ) around all your $content data instead of double quotes ( " ). That might be part of your problem. Also these PDF generators don't like malformed HTML code do any mistake at all will corrupt the output. I can see where it's doing the PDF generation here:

require_once(dirname(__FILE__).'/html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('P','A4','fr');
$html2pdf->WriteHTML($content);
$html2pdf->Output('exemple.pdf'); 

You're passing in your HTML code through your $content variable and then attempting to save it to example.pdf inside the current directory. Does your webserver have permissions to save into that directory? Should you be trying to save into a different directory? If it still doesn't work, try passing in the most basic HTML you can think of and see if that works, then keep working up your $content variable by continuously adding pieces to it until you get to either:

a) a working code sample using your entire $content piece.

----or-----

b) the specific line that breaks your PDF generator.

 

Try this to see if it works:

require_once(dirname(__FILE__).'/html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('P','A4','fr');
$html2pdf->WriteHTML("<html><body>Hello</body></html>");
$html2pdf->Output('exemple.pdf'); 

If that doesn't work then your issue is somewhere further back in the code. Or if by "doesn't work" you mean that it doesn't save the PDF,, then you likely don't have write permissions in the directory where you're trying to save the example.pdf which here is your current directory and I can tell you now that would be an enormous security risk. I cringe at the thought of it.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.