This have been bugging me for a few hours. When i try to produce pdf, i got this error:
1) Warning: Division by zero in C:\xampp\htdocs\KPAPMS\PHP\lib\pdftable.php on line 540
2) FPDF error: Some data has already been output, can't send PDF file
i just use the existing code to generate pdf(fpdf).
this is my code example
<?php
$sql = "SELECT * from vesservice";
$res = mysql_query($sql);
$hdd= "<table width=100%>
<tr><th width=100><strong>Company</strong></th><th><strong>: Kuching Port Authority</strong></th><th></th>
<th>Date / Time: ".$date."</th></tr>
<tr><th width=100><strong>Title</strong></th><th><strong>: Water Supply for SCN</strong></th><th></th><th></th></tr>
<tr><th colspan=4><hr></th></tr>
<tr>
<th><strong>SCN</strong></th><th>:</th>
<th><strong>Berth Date</strong></th><th>:</th></tr>
<tr>
<th><strong>Debtor Code</strong></th><th>:</th>
<th><strong>Expected Depart Date / Time</strong></th><th>:</th></tr>
<tr>
<th></th><th></th>
<th><strong>Actual Depart Date / Time</strong></th><th>:</th></tr>
<tr><th colspan=4><hr></th></tr>
</table>";
$tables="<table width=100%>
<tr align=center>
<th>Service Reference</th>
<th>Service Code</th>
<th>Water Supply Reference</th>
<th>Water Supply Sequence</th>
<th>Tariff Code</th>
<th>Tariff Description</th>
<th>UOM</th>
<th>Service Date</th>
<th>Requested Time</th>
<th>Volume<br />(Tonne)</th>
<th>Service Date</th>
<th>Started Time</th>
<th>Volume<br />(Tonne)</th>
<th>Service Date</th>
<th>Ended Date</th>
<th>Duration</th></tr>";
while($rs=mysql_fetch_assoc($res))
{
$tables.= "<tr align=center>
<td>".$rs['serv_opt']."</td>
<td>".$rs['dt_code']."</td>
<td>".$rs['scn']."</td>
<td>".$rs['term_code']."</td>
<td>".$rs['serv_cat']."</td>
<td>".$rs['serv_code']."</td>
<td>".$rs['activ_cnt']."</td>
<td>".$rs['serv_date_req']."</td>
<td>".$rs['serv_shift_req']."</td>
<td>".$rs['serv_qty']."</td>
<td>".$rs['serv_ref']."</td>
<td>".$rs['res_serv_date']."</td>
<td>".$rs['res_serv_time']."</td>
<td>".$rs['new_serv_date']."</td>
<td>".$rs['new_serv_time']."</td>
<td>".$rs['new_serv_qty']."</td>
</tr>";
}
$tables.="</table>";
//echo $hdd.'<br />'.$tables;
$p = new PDFTable('L','mm','a4');//set page orientation P/L
$p->SetFont('Times','',10);
$p->headerTable=$hdd;
$p->AddPage();
$p->htmltable($tables);
//ob_end_clean();
$p->output("Water Supply.pdf",'I'); //D=download
When i uncommet the ob_end_clean, it can generate the pdf output, but only print $tables but the header is not printed.
Please help me, which part i did wrong.
You can try insert ob_end_clean(); before outputing.
Example
<?php
require('fpdf.php');
$pdf = new FPDF();
//your code for eneration of the pdf
ob_end_clean();
$pdf->Output();
?>
Ok if you want FPdf to work properly, there cannot be any output at all beside what fpdf generates. You can solve the problem deleting all new line characters found at the end of the .php files, using the following regular expression
\?>\n\z
replaced with
\?\n
For example:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Ok, OK
$pdf->Output();
?>
But this won't work
<?php
echo "You don't sent before output";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'OK oK);
$pdf->Output();
?>
Related
I'm new with PHP, I'm developping a WEB application that display a table with informations from an SQL server DATA BASE, the problem that I want to add a button to generate an EXCEL file that contains the table displayed? Is that possible??
#Ranjit this is the PHP code that displays the table and generate the excel file
edit 1
<?php
$ch="";
if(isset($_POST['historique']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$ch= "(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
?>
<table id="tab" border="1">
<tr>
<th><font color="red">Date</font></th>
<th><font color="red">Agent</font></th>
<th><font color="red">numéro</font></th>
</tr>
<?php
$search = " // my query
where operationDate between" .$ch;
$stmt = mssql_query($search);
while ($data = mssql_fetch_assoc($stmt))
{
?>
<tr>
<td><?php echo utf8_encode ($data['operationDate']);?></td>
<td><?php echo utf8_encode ($data['fullName']);?></td>
<td><?php echo utf8_encode ($data['number']);?></td>
</tr>
<?php
} }
?>
</table>
<?php
}
$output ='';
if(isset($_POST['excel']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$rq = "// my query
where operationDate between" ."(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
$res = mssql_query($rq);
if(mssql_num_rows($res)>0)
{
$output.='<table border=1>
<tr>
<th>Date</th>
<th>Depanneur</th>
<th>numéro</th>
</tr>
';
while ($row=mssql_fetch_array($res))
{
$output .='
<tr>
<td>'.$row["operationDate"].'</td>
<td>'.$row["fullName"].'</td>
<td>'.$row["number"].'</td>
</tr>';
}
$output .='</table>';
header("Content-Type: application/xls;charset=UTF-8");
header("Content-Disposition: attachement; filename=file.xls");
echo $output;
//mssql_close($conn);
}}}
?>
You'll have to select the data manually then insert them into the excel sheet, there's php library called PHPEXCEL you can use it.
See this
http://www.c-sharpcorner.com/article/export-to-excel-in-php-with-my-sql/
There are some nice packages out there to generate excel files such as
Box Spout and PHP Spreadsheet.
The documentation of both packages is very clear any you will be generating excel files within minutes of browsing through documentation.
Yes,
It is possible. You can follow this
1) Connect to database:
2) Define a filename of excel
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
$fp = fopen('database.xls', "w");
$schema_insert = "";
$schema_insert_rows = "";
//start of printing column names as names of MySQL fields
Sources - http://www.anillabs.com/2010/03/how-to-create-excel-file-with-mysql-data-using-php-code/
so I am having trouble exporting the data from MySQL into excel
$output = '';
if(isset($_POST["export_excel"]))
{
$sql = "SELECT * FROM Logs ORDER BY item";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<table class="table bordered="1">
<tr>
<th>Sort</th>
<th>Unit Size</th>
<th>Quantity</th>
<th>Price per Unit</th>
<th>Time</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["Sort"].'</td>
<td>'.$row["Unit Size"].'</td>
<td>'.$row["Quantity"].'</td>
<td>'.$row["Price per Unit"].'</td>
<td>'.$row["Time"].'</td>
</tr>
';
}
$output .= '</table>';
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=download.xls");
echo $output;
}
}
so when I hit the export button on my index.php page it outputs the data in this format: Google Sheets Link to the excel file
<table class="table bordered="1">
<tr>
<th>Sort</th>
<th>Unit Size</th>
<th>Quantity</th>
<th>Price per Unit</th>
<th>Time</th>
</tr>
<tr>
<td></td>
<td>45</td>
<td>0</td>
<td>0</td>
<td>2016-08-11 16:53:12</td>
</tr>
<tr>
<td></td>
<td>6</td>
<td>0</td>
<td>0</td>
<td>2016-08-11 16:53:12</td>
</tr>
</table>
so it outputs the right data but just the formating is off, here is what it looks like on the index.php page:
What the excel file should look like
do if anyone can tell me what I am doing wrong that be wonderful!
Thank you in advance!
Perhaps a little bit of a cheat outputting as csv rather than proper xls but it should more or less work.
<?php
if( isset( $_POST["export_excel"] ) ) {
ob_clean();
$sql = 'select * from logs order by item';
$result = mysqli_query( $connect, $sql );
if( mysqli_num_rows( $result ) > 0){
$delimiter=',';
$enclosure='"';
/* rather than create an actual file, use an output buffer and write to that */
$output=fopen('php://output','w+');
/* add column headers */
$headers=array( 'Unit Size', 'Quantity', 'Price_per_Unit', 'Time' );
/* write the headers to the output stream */
fputcsv( $output,$headers, $delimiter, $enclosure );
/* loop through recordset and add that to the stream */
while( $row = mysqli_fetch_array( $result ) ) {
fputcsv( $output, $row, $delimiter, $enclosure );
}
fclose( $output );
/* set the headers accordingly */
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=download.csv');
/* send the new content */
ob_flush();
}
}
?>
If i understand you correctly you want to export data into excel. In that case just changing the headers won't work because excel is not about table tags, What you need is a library for writing the contents into an excel format file and then make user download the same. Have a look at phpExcel.
You can also see in the example here on how to properly insert data in excel using the same.
I have made the following file:
test.php
<?php
require 'vendor/autoload.php';
use mikehaertl\wkhtmlto\Pdf;
$htmlString = <<<EOT
<!DOCTYPE html>
test
</html>
EOT;
$pdf = new Pdf($htmlString);
$pdf->setOptions(array(
'orientation' => 'landscape'
));
$pdf->saveAs('new.pdf');
?>
When I run from the command line (Ubuntu 12.x):
sudo php test.php
I get a file that shows up in my directory and works as intended. However now take the following file where I am trying to apply the above to a real world scenario - note: when I echo $htmlString I get a valid and expected string.
testPDF.php
<?php
// Start session and check if user is logged in
session_start();
if(!isset($_SESSION['permission']))
{
die('Please login.');
}
// Dependencies
require 'vendor/autoload.php';
use mikehaertl\wkhtmlto\Pdf;
require 'database.php';
// Initialize
$client = $db->real_escape_string($_GET['client']);
$start_date = $db->real_escape_string($_GET['start_date']);
$end_date = $db->real_escape_string($_GET['end_date']);
$jobs = array();
$htmlString = '';
// Get list of jobs from DB & save to array
$query = "SELECT somecolumns FROM mydatabase WHERE start_date > '{$start_date}' AND end_date < '{$end_date}' AND client = '{$client}'";
if(!$result = $db->query($query))
{
die('There was an error running the query [' . $db->error . ']');
}
while($r = mysqli_fetch_assoc($result))
{
$jobs[] = $r;
}
// Loop through jobs array and formulate HTML string
foreach($jobs as $value)
{
$id = $value['id'];
$name = $value['name'];
$tech = $value['tech'];
$time_closed = $value['time_closed'];
$time_total = $value['time_total'];
$time_charged = $value['time_charged'];
$description = $value['description'];
$htmlString = $htmlString . <<<EOT
<h4 style="text-align: center;">{$id} - {$name}</h5>
<table id="simple-table" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="width: 180px;">Date</th>
<th>Description</th>
<th style="width: 50px;">Duration</th>
<th style="width: 150px;">Time Charged</th>
<th style="width: 150px;">Technician</th>
</tr>
</thead>
<tbody id="jobs_start">
<tr>
<td>{$time_closed}</td>
<td>{$description}</td>
<td>{$time_total}</td>
<td>{$time_charged}</td>
<td>{$tech}</td>
</tr>
</tbody>
</table>
EOT;
}
$pdf = new Pdf($htmlString);
$pdf->setOptions(array(
'orientation' => 'landscape'
));
$pdf->saveAs('new.pdf');
?>
When I try to run the above by browsing to testPDF.php as a logged in user, I get nothing. No file is generated and no error/warning in the error logs. I've tried using $pdf->send() as well but no success.
My initial thought that this is a permissions issue, however I've tried setting testPDF.php to owner root and permission 755 but it still does not resolve the issue.
The issue is that when sending a HTML string to the pdf object, it looks for the tag to determine if it's html.
The first example has a HTML tag, while the 2nd file does not have any html tag thus is fails, silently.
https://github.com/mikehaertl/phpwkhtmltopdf/blob/master/src/Pdf.php
I have developed a software with PHP and report with TCPDF. It runs well, but after importing lot of data in MySQL, the PHP can't produce the report before the browser times out. I've tried with the latest firefox and Chrome versions.
This my script:
<?php
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
// create new PDF documentation
include "koneksi.php"; //file conection
$bln=$_POST[BLN]; //for catch month
$thn=$_POST[THN]; //for catch year
$exp=$_POST[EXP]; //for catch expedition name
if(empty($exp))
{
$sql = "SELECT * FROM tb_exp_local where bulan = '$bln' AND tahun = '$thn'";
}
elseif($exp != "")
{
$sql = "SELECT * FROM tb_exp_local where bulan = '$bln' AND tahun = '$thn' AND nama_exp = '$exp'";
}
$hasil = mysql_query($sql);
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set font
$pdf->SetFont('times', '', 11);
// landscape
$pdf->addPage( 'L', 'LETTER' );
//this for convert html to pdf with html function
$html = '
<table border="1" cellspacing="3" cellpadding="4">
<tr><td colspan="9" align="center"><h2>Form Pantauan Expedisi Export</h2></td></tr>
<tr>
<th align="center"><b>Tanggal</b></th>
<th align="center"><b>Nama Expedisi</b></th>
<th align="center"><b>Nama Distributor</b></th>
<th align="center"><b>Kota Tujuan</b></th>
<th align="center"><b>No Faktur</b></th>
<th align="center"><b>Kondisi Armada Pengiriman</b></th>
<th align="center"><b>Ketepatan Jumlah</b></th>
<th align="center"><b>Ketepatan Waktu Kirim</b></th>
<th align="center"><b>Keterangan</b></th>
</tr></table>';
while ($data = mysql_fetch_array($hasil))
{
$html .= '<table border="1"><tr><td align="center">'.$data['tgl'].'</td>
<td align="center">'.$data['nama_exp'].'</td>
<td align="center">'.$data['nama_dist'].'</td>
<td align="center">'.$data['kota_tujuan'].'</td>
<td align="center">'.$data['faktur'].'</td>
<td align="center">'.$data['konarmada'].'</td>
<td align="center">'.$data['tepatjml'].'</td>
<td align="center">'.$data['tepatwaktu'].'</td>
<td align="center">'.$data['ket'].'</td>
</tr></table> ';
}
$pdf->writeHTML($html, true, false, true, false, ''); //for generate
$pdf->Output('FormPantauExpLocalAll', 'I'); // for generate pdf file
?>
Server timeout does not depend on browser. Try using set_time_limit(60) inside your loop:
while ($data = mysql_fetch_array($hasil))
{
set_time_limit(60);
$html .= '(...)';
}
Also, try adding INDEX to your DB on (bulan, tahun, nama_exp) columns, it should speed up the retrieval process. Also, be aware that you may have run out of memory during the process (check your PHP logs on your server)
I am new to FPDF.
But i am trying like below. How can I create a PDF from HTML tags using FPDF?
<?php
require('fpdf.php');
include (connection.php)
$result = mysql_query("SELECT * FROM emp");
<!--- I don't know how to add the html tag here -->
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Output();
?>
below is my PHP program
<?php
include (connection.php)
$result = mysql_query("SELECT * FROM emp");
?>
<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td> <?php print $row['FirstName']; ?></td>
<td> <?php print $row['LastName']; ?></td>
</tr>
<?php
}
?>
</table>
<?php
mysql_close($con);
?>
I think you should consider to use HTML2FPDF
Usage example available at the bottom of this blog post.
Check as well this other SO question: https://stackoverflow.com/questions/910243/how-to-convert-an-html-to-pdf-in-php-using-fpdf-lib-1-6
PHP code to convert HTML to PDF works fine on my end.
The following code converts a web page and sends the generated PDF to the browser:
require 'pdfcrowd.php';
// create an API client instance
$client = new Pdfcrowd("username", "apikey");
// convert a web page and store the generated PDF into a variable
$pdf = $client->convertURI('http://www.google.com/');
// set HTTP response headers
header("Content-Type: application/pdf");
header("Cache-Control: max-age=0");
header("Accept-Ranges: none");
header("Content-Disposition: attachment; filename=\"google_com.pdf\"");
// send the generated PDF
echo $pdf;
You can also convert raw HTML code, just use the convertHtml() method instead of convertURI():
$pdf = $client->convertHtml("<body>My HTML Layout</body>");
The API lets you also convert a local HTML file:
$pdf = $client->convertFile("/path/to/MyLayout.html");
go here for download API Visit