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
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/
I'm trying to display the content of a php file to a div.
<div contenteditable="true" id="highlight">
<?php
echo file_get_contents( "/path/test.php" );
?>
</div>
test.php
<?php
require_once (lib.php');
/*
some comments here
*/
session_cache_limiter('private, must-revalidate');
header('Pragma: public');
#ob_start();
#session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
// INCLUDES
define('FPDF_FONTPATH', "path/font/");
// print_r($_GET);
?>
.......................
But the content in the div is displaying from this line only : // print_r($_GET);. I need to display the entire content of the file.
Can anyone help me to fix this? Thanks in advance.
Because the HTML parser of your browser sees <?php as an HTML element it will be commented out. You have to convert < and > to their equivalent HTML entities.
You can do this using htmlspecialchars (using <pre></pre> to keep the new lines from the actual file):
<div contenteditable="true" id="highlight">
<pre><?php // this should be directly after pre to prevent white-space from appearing before the code from the file
echo htmlspecialchars(file_get_contents( "43677696_test.php" ));
?>
</pre>
</div>
You can see the output here.
<?php
include ('mpdf/mpdf.php');
$mpdf = new mpdf;
ob_start();
?>
<html>
<head></head>
<body>
My various content with table, dropdown menu and 2 include files.
</body>
</html>
<?php
$html = ob_get_contents();
ob_end_clean();
$mpdf->Output();
exit;
?>
Wondering why this function doesn't work and will only output empty pdf file. I have tried many ways but it just doesn't work. I have placed this function at the beginning of my code but it always outputs an empty file.
Try this code:-
<?php
$html = ob_get_contents();
ob_end_clean();
// You need to write html
$mpdf->WriteHTML($html);
// define path of your output file and set mode 'F' for saving
$mpdf->Output('filename.pdf','F');
exit;
?>
I am working on WordPress website. And on front-end I am giving the functionality to create a resume online & on submitting the form he will get a option to download & print the resume in PDF format. Till now everything is working fine If I am passing a simple html file to convert into PDF. But I want to create a PDF out of the fields of resume inserted in the database. If I am passing the plain html file for conversion it works fine.
But what if I want to create a dynamic PDF file of the PHP file.
Here is my tried code:
I have used html2pdf conversion library for this.
This is a file from which the call to test.php goes.
require("html2pdf/html2fpdf.php");
$htmlFile = "test.php";
$buffer = file_get_contents($htmlFile);
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('test.pdf', 'F');
And the test.php file is:
<html>
<body>
<?php
$username = "";
$password = "";
$hostname = "";
$dbname = "";
// Create connection
$con = mysqli_connect($hostname, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo $result = mysqli_query($con,"SELECT * FROM wp_resume ORDER BY id DESC LIMIT 1");
echo "hioooooo";
while($row = mysqli_fetch_array($result))
{
?>
<div>
<label>First Name</label><script type="text/php"><?php echo $row['firstName']; ?></script><br>
<label>Last Name</label><script type="text/php"><?php echo $row['lastName']; ?></script><br>
</div>
<?php
}
?>
</body>
</html>
Now after submitting the form I am getting a PDF file which contains only this data:
First Name
Last Name
And I want all the details of the entry inserted. Clearly this ignores the code inside the <?php ?> tags. So even if I used var_dump(), I didn't get anything.
SO please help me out in this guys. How can I pass the PHP data to PDF file.
Hey I got the solution for this. And the correct code is:
require("html2pdf/html2fpdf.php");
$html = '<h2>Resume</h2>';
$query = "SELECT * FROM wp_resume order by id desc limit 1";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$html .= '<div>
<label>First Name</label> '. $row['firstName'].'<br>
<label>Last Name</label> '. $row['lastName']. '<br>
</div>';
}
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($html);
$pdf->Output('test.pdf', 'F');
I hope this will help somebody....
file_get_contents returns the content of a file, without it being parsed as PHP...
Replace
$buffer = file_get_contents($htmlFile);
With
ob_start();
include($htmlFile);
$buffer = ob_end_clean();
What we are doing: opening an output buffer (this prevents the echo from going to the client as they appear) then we include the PHP file so it gets parsed and all. Remember all the echo's are in the output buffer, so grab it with ob_end_clean() and use the generated HTML to make a PDF.
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.