I'd installed the MPDF utility in order to convert HTML&CSS to PDF reports.
So far things have been working just fine, until I've tried converting certain page to PDF ,and there's no output.
I have to mention that i'm able to display the page regularly through browser - the problem only comes up when i'm trying to convert it to PDF - then I receive blank page. Moreover, there are no encoding problems (part of the output is written in Hebrew, but I've already overcame this obstacle)
Here's part of the code :
if($customer!=$tempCustomer)
{
if($tempCustomer!="")
{
$html.=("</table>");
$html.=("</BR>סהכ".$sumTotal."</BR>");
$html.=("</BR>משטחים".$sumPallets."</BR>");
}
$sumTotal=0; //RESET SUM OF EACH CUSTOMER
$sumPallets=0; //RESET PALLETS COUNT
$html.=("</div>");
$html.=("<div class='subTable'>");
// $html.=("לקוח: ".$customerName."</br>");
$sumTotal=0;
$sumPallets=0;
$tempCustomer=$customer;
$html.=("<table border='3'
<tr><td>מגדל</td><td>תאריך</td><td>תעודה</td><td>פריט</td><td>סוג</td><td>גודל</td><td>כמות</td><td>משקל</td><td>מחיר
מכירה</td><td>סכום</td><td>משטחים</td></tr>");
$html.=("<tr>");
$html.=("<td>".$grower."</td>");
$html.=("<td>".$date."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$item."</td>");
$html.=("<td>".$type."</td>");
$html.=("<td>".$size."</td>");
$html.=("<td>".$quantity."</td>");
$html.=("<td>".$weight."</td>");
$html.=("<td>".$price."</td>");
$html.=("<td>".$total."</td>");
$html.=("<td>".$pallet."</td>");
$html.=("</tr>");
$sumTotal+=$total;
$sumPallets+=$pallet;
}
else
{
$html.=("<tr>");
$html.=("<td>".$grower."</td>");
$html.=("<td>".$date."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$item."</td>");
$html.=("<td>".$type."</td>");
$html.=("<td>".$size."</td>");
$html.=("<td>".$quantity."</td>");
$html.=("<td>".$weight."</td>");
$html.=("<td>".$price."</td>");
$html.=("<td>".$total."</td>");
$html.=("<td>".$pallet."</td>");
$html.=("</tr>");
$sumTotal+=$total;
$sumPallets+=$pallet;
}
/*
$html.=("<td>".$form."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$form."</td>");
$html.=("<td>".$form."</td>");
$html.=("</tr>");
*/
}
$html2='אבדרכדכגכגכגכג';
$html3='אבדרכדכגכגכגכג';
//==============================================================
//MPDF SETTINGS - CONTINUE
$mpdf->SetAutoFont();
$mpdf->autoFontGroupSize = 1;
$mpdf->SetDirectionality('rtl');
$mpdf->useLang = true;
$mpdf->WriteHTML($html);
$mpdf->Output();
exit;
Any suggestions?
Thanks in advance
Have you tried debugging it? Per mpdf's site: If you get nothing but a blank screen on your browser, it may be because there is a script error. Turn on debugging at the start of your script.
<?php
include("../mpdf.php");
$mpdf=new mPDF();
$mpdf->debug = true;
$mpdf->WriteHTML("Hallo World");
$mpdf->Output();
?>
If the above works, then it's something with your code. Sometime, even a single space before any html output can throw off MPDF
First of all, If you get nothing but a blank screen on your browser, it may be because there is a script error. Turn on debugging at the start of your script.
// Require composer autoload
require_once __DIR__ . '/vendor/autoload.php';
try {
$mpdf = new \Mpdf\Mpdf();
$mpdf->debug = true;
$mpdf->WriteHTML("Hello World");
$mpdf->Output();
} catch (\Mpdf\MpdfException $e) { // Note: safer fully qualified exception
// name used for catch
// Process the exception, log, print etc.
echo $e->getMessage();
}
After that if there is any error like
Data has already been sent to output, unable to output PDF file
This means before creating pdf with mPDF some data is stored in the buffer which is sended to the browser. Therefore it is unable to create PDF.
Just do this..
Add this below php built-in function at the first line of your page were you are preparing data for pdf.
op_start();
And add this php built-in function before mPDF code (before where you are calling mpdf)
ob_end_flush();
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($html);
$mpdf->Output();
So that it will clear all buffer output before processing mPDF.
Make sure if you use any functions then keep it in the same page.
<?php
include_once("mpdf-master/mpdf.php");
include_once('../../../../wp-load.php');
$htm = get_template_directory_uri().'/admin/_invoice.php?id='.$_GET['id'];
$html = file_get_contents("$htm");
$mpdf=new mPDF('c');
$mpdf->WriteHTML($html);
$mpdf->Output();
?>
You can try link this.but you will get seconde page blank but in first page you will get the detail.
Thanks
Sanket.
Related
I have managed to create a graph using JpGraph, I want to now take it a step further and embed this graph in my template/view php file.
So I put the graph code into a seperate php file to then embed however, when I try to embed it via
<embed src="templates/ctl008/graphshow.php" height=80em; width=160em;> </embed> it leaves me with a requested URL not found error. I have fiddled with the path and tried just: graphshow.php, ctl008/graphshow.php and other such variations. Is it my path that is not correct or is there something else I am missing? I have also tried to embed it with <img src="graphshow.php" /> . A funny quirk is when I turn on ini_set('display_errors', 1); error_reporting(E_ALL); and try to view the graph on its own I am left with an error message: JpGraph Error: HTTP headers have already been sent. Caused by output from file gd_image.inc.php at line 92. but if i turn off the error_reporting it displays the graph as expected. I would appreciate any pointers in the right direction with this :)
Here is my graphshow.php file:
<?php require_once ('../library/include/jpgraph/src/jpgraph.php');
require_once ('../library/include/jpgraph/src/jpgraph_line.php');
require_once ('../library/include/jpgraph/src/jpgraph_bar.php');
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
$gasArray = array();
foreach($searchArray as $gArray){
$gasArray[] = $gArray['GASVB'];
}
$stromArray = array();
foreach($searchArray as $sArray){
$stromArray[] = $sArray['STROVB'];
}
$olArray = array();
foreach($searchArray as $oArray){
$olArray[] = $oArray['OLVB'];
}
if(!empty($gasArray) || !empty($stromArray) || !empty($olArray)){
ob_end_clean();
$width= 1200;
$height = 400;
$graph = new Graph($width, $height);
$graph->SetScale('intint');
$graph->title->Set('Energie Verbrauch');
$graph->SetMargin(80,25,30,80);
$graph->xaxis->title->Set('Datum');
$graph->yaxis->title->Set('Verbrauch');
// print_r($dateArray);
$lineGas = new LinePlot($gasArray);
$lineGas->SetLegend('Gas');
$lineStrom = new LinePlot($stromArray);
$lineStrom->SetLegend('Strom');
$lineOl = new LinePlot($olArray);
$lineOl->SetLegend('ÖL');
$graph->Add($lineGas);
$graph->Add($lineStrom);
$graph->Add($lineOl);
$graph->Stroke();
}
?>
I'd like to start off with a few helpful links:
JpGraph Error: HTTP headers have already been sent
http://www.digialliance.com/docs/jpgraph/html/2210intro.html
https://coursesweb.net/php-mysql/jpgraph-graph-charts-plots-php
https://jpgraph.net/download/manuals/chunkhtml/ch05s05.html
now that that is out of the way, how I managed to get it working:
Starting with the advice/help in the above StackOverflow link I turned my seperate php file into a function the final line of my graphshow.php function was this: $graph->Stroke("charts/graphEnergy.png"); where charts is the folder I am saving in and graphEnergy.png is the name of the file being saved.
then in my view/template page I require_once('chart/ctl008/graphshow.php'); made my php file accessible, called my function like so generateGraph($gasArray, $stromArray, $olArray); and then in the html section embedded the graph with <img src="./charts/graphEnergy.png" /> What really tripped me up was needing to call the graph.png with the ./ before the charts/graphEnergy.php, and then I was able to display my bootiful graph on my view/template page. I hope this helps someone in the future :)
BoogaBooga
I am trying to print my content to PDF using Mpdf tool . The code is working in localhost , But when i tired same code in server its not working giving some eroor "mPDF error: Some data has already been output to browser, can't send PDF file".
My code is :
<?php
$address = "banglore rt nagar";
$template_data = " hello this is test ##ADDRESS## adress";
$template_data = str_replace('##ADDRESS##', $address , $template_data);
ob_end_clean();
include 'MPDF57/mpdf.php';
$mpdf=error_reporting(E_STRICT);
$mpdf=new mPDF('win-1252','A4','','',15,10,16,10,10,10);
$mpdf->Bookmark('Start of the document');
$mpdf->SetDisplayMode('fullpage');
$mpdf->WriteHTML($template_data);
$mpdf->Output();
exit();
?>
i have tried lot of solutions . but nothing works good . any help ?
Use ob_start(); after the <?php tags . hope it will helps you .
more ohttp://php.net/manual/en/function.ob-start.php
I am converting an html file to PDF by using mPdf, but the returned PDF file includes blank pages. I want to delete those blank pages.
Had the same problem and realized that my CSS was forcing these page breaks. Make sure you don't have this in your CSS:
page-break-after: always;
It may be for many reasons:
1) Make sure the elements doesn't have unnecessary margins nor Paddings
2) Configure correctly the page properties (specially margins) :
$page_orientation = 0;
$page_size = 'Letter';
$page_margins = array('LEFT(int)','RIGHT(int)','UP(int)','BOTTOM(int)');
$pdf_output = 'I';
$css_files = array(
'path/file.css',
'path/file_2.css',
);
$orientationPage = array('','-L');
/* ===== [ MPDF ] =====*/
$mpdf=new mPDF('utf-8', $page_size.$orientationPage[$page_orientation],'','',$page_margins[0],$page_margins[1],$page_margins[2],$page_margins[3]);
// Loading CSS
for($i = 0; $i < count($css_files); $i++){
$stylesheet = file_get_contents('../../'.$css_files[$i]);
$mpdf->WriteHTML($stylesheet,1); // 1 para indicar que es CSS
}
// Set header & Footer (This are variables with html code)
$mpdf->SetHTMLHeader($header);
$mpdf->SetHTMLFooter($footer);
$mpdf->SetDisplayMode('fullpage');
$mpdf->SetTitle($title);
$mpdf->WriteHTML($html); // <-- insert HTML
// Create PDF
$mpdf->Output($titulo.'.pdf',$pdf_output);
3) Make sure you haven't unnecessary "Page Breaks" on the HTML
<pagebreak type="NEXT-ODD" resetpagenum="1" pagenumstyle="i" suppress="off" />
I hope it can help you!
I had the same problem and i fixed it by removing the AddPage property from my code
I changed the following code
// Code with bug
$mpdf = new mPDF('utf-8', array(380,500));
$mpdf->WriteHTML($htmlContent);
$mpdf->AddPage('P'); // It will add extra page - I that i removed this line
$mpdf->Output();
Into this
// code after resolving the bug
$mpdf = new mPDF('utf-8', array(380,500));
$mpdf->WriteHTML($htmlContent);
$mpdf->Output();
I am getting problem in anchor tag while export to PDF.Anchor tag is working for static url like http:google.com but it is not working for dynamic url.I am using mpdf module for PDF.
$url = $fullBaseUrl.'/designers/attachment/time/'.$value['filetime'].'/uploadTab/imgattach';
// http://localhost/msme_latest/designers/attachment/time/1394432246/uploadTab/imgattach
$html= ''.$value['filename'].'';
// echo $html; die;
$mpdf->WriteHTML($html);
$mpdf->Output();
exit;
When i echo my code $html it is giving my link properly.But when i export this code in PDF it is not giving any kind of link PDF.
Any help will be appriciated.
For solve this problem you have to make just i change in mpdf.php
Actual Code is in mpdf.php on line no.20146
if(isset($vetor[1]) and $vetor[1] != '') //LINK
{
if (strpos($vetor[1],".") === false && strpos($vetor[1],"#") !== 0) //assuming every external link has a dot indicating extension (e.g: .html .txt .zip www.somewhere.com etc.)
{
//Repeated reference to same anchor?
/*
while(array_key_exists($vetor[1],$this->internallink)) $vetor[1]="#".$vetor[1];
$this->internallink[$vetor[1]] = $this->AddLink();
$vetor[1] = $this->internallink[$vetor[1]];
*/
}
$this->HREF = $vetor[1]; // HREF link style set here ******
}
and you have just comment line of code (line number:20151 to 20153)
/*
while(array_key_exists($vetor[1],$this->internallink)) $vetor[1]="#".$vetor[1];
$this->internallink[$vetor[1]] = $this->AddLink();
$vetor[1] = $this->internallink[$vetor[1]];
*/
and your pdf will accept all link include "localhost" and other external links.
use Ip address instead of localhost or use Live server url it is working for me
<?php
$fullBaseUrl = "http://127.0.0.1/meme_latest";
$url = $fullBaseUrl.'/designers/attachment/time/'.$value['filetime'].'/uploadTab/imgattach';
//(http://localhost/msme_latest/designers/attachment/time/1394432246/uploadTab/imgattach)
$html= 'Test link';
//echo $html; die;
include("../mpdf.php");
$mpdf=new mPDF();
$mpdf->WriteHTML($html);
$mpdf->Output();
exit;
?>
I have a html document which marks up a report. I have a button on this page "Export as pdf". However I am not sure how to export html into a pdf..Are there any tools out there that anyone recommends for such a task..
EDIT: In more detail:
I have the following php:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
$sectionTwo = array();
$sectionThree = array();
$sectionFour = array();
$sectionFive = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$section = $row['sectionId'];
switch($section){
case '1':
$sectionOne[] = $row;
break;
case '2':
$sectionTwo[] = $row;
break;
case '3':
$sectionThree[] = $row;
break;
case '4':
$sectionFour[] = $row;
break;
case '5':
$sectionFive[] = $row;
break;
default:
break;
}
}
}else{
//error - sql failed
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
Export as PDF
</div>
<h3>Biological Information</h3>
<?php
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
?>
<h3>Fatigue and Recovery</h3>
<?php
foreach($sectionTwo as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Illness and Injury</h3>
<?php
foreach($sectionThree as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Training Sessions</h3>
<?php
foreach($sectionFour as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>General Feedback</h3>
<?php
if(count($sectionFive)>0){
foreach($sectionFive as &$value){
echo($value['question'].' : '.$value['answer']);
}
}else{
echo("User didn't leave any feedback");
}
echo("<br/>");
?>
</body>
</html>
<?php
}
?>
This displays the following:
So if I'm using fpdf, what is the best way to export the following as a pdf? Should I write a fpdf function in the same php file or is it best to write a separate php file which creates and displays the pdf (which means I would have to post all relevant data to this file)...
Use FPDF library for php
check here
The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.
<?php
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:
$pdf=new FPDF('P','mm','A4');
It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).
Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().
To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:
$pdf->SetFont('Arial','B',16);
We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:
$pdf->Cell(40,10,'Hello World !',1);
Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.
I've found this software quite useful: http://code.google.com/p/wkhtmltopdf/
It is true that you'll have to exec() it from your code, but it works very good and uses webkit as the backend engine (allowing javascript also, and many other features to customize the pdf creation), saving a lot of code.
Hope it helps, we're using it here and it works like a charm.
EDIT: try the static binaries. untar and ready to go :)
You may also use an online tool Pdfcrowd API
Its easy to integrate and provides much in its free edition. You may check
PDFCrowd Official Site
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/');
//You can also convert raw HTML code, just use the convertHtml() method instead of convertURI()
$pdf = $client->convertHtml("<body>My HTML Layout</body>");
//Or use convertFile() to convert a local HTML file
$pdf = $client->convertFile("/path/to/MyLayout.html");
// set HTTP response headers
header("Content-Type: application/pdf");
header("Cache-Control: no-cache");
header("Accept-Ranges: none");
header("Content-Disposition: attachment; filename=\"google_com.pdf\"");
// send the generated PDF
echo $pdf;
Another much easier way is with HTML2FPDF.
HTML2FPDF is a PHP Class library that uses the FPDF class library to convert HTML files to PDF files. This library consist of three classes namely PDF, HTML2FPDF and FPDF (modified FPDF class). The class PDF extends the class HTML2FPDF that extends the class FPDF.
Now let us see, how to convert a sample html page into a PDF file using HTML2FPDF Library. The html page contains a table that lists a few nations with their corresponding national flags. Below is the code for the conversion.
<?
require('html2fpdf.php');
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen("sample.html","r");
$strContent = fread($fp, filesize("sample.html"));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output("sample.pdf");
echo "PDF file is generated successfully!";
?>
First, we need to include the html2fpdf.php file that contains the HTML2FPDF class and an object is created using the constructor HTML2FPDF(). Then a new page is added to the pdf document using the function AddPage(). The html contents are read from the sample.html file using file functions. Then the html contents are written in to the pdf format using WriteHTML() function. To view the html file, click here and to view the generated pdf, click here. The above sample code with the sample html file and images and the html2fpdf class libraries can be downloaded here.
The HTML2FPDF class library will be working best with the XHTML 1.0. Also the class does not support all the features available with HTML. To know the supported HTML tags and other features, Please refer http://html2fpdf.sourceforge.net.
I recommend you to use this since it's much easier and friendly.