PHP Create PDF
file on fly With PDFlib
This tutorial demos how to create a PDF file on fly with
PDFlib.
The PDF ( portable document format) file is an versatile
format for transferring a document over the Internet.
Many companies use the PDF format to transfer contracts, manuals,
and other documents over the Internet without trying to convert them
to HTML or changing the format of the document in any way.
This code will be useful
if you were considering creating invoices, reports or any other
hardcopy file for your client.
Testing PDFlib installation
This tutorial needs PdfLib properly installed. PDFlib
is available for download at http://www.pdflib.com/products/pdflib/index.html, but requires
that you purchase a license for commercial use.
First, you need test if your PHP supports PDFlib or not.
Copy the following code to a file (phpinfo.php) and save it in your
web root. Then launch it like : http://your-web-site/phpinfo.php.
If your PHP supports PDFlib, you will see an section
looks like the following::
PDF Support: enabled
PDFlib Gmbh Version: 5.0.3
Revision: $Revision: 1.112.2.11 $ |
Get input from Client
We will put client input into our PDF dynamically. Use the following
code to get client input.
<html>
<head>
<title>Name Entry Level</title>
</head>
<body>
<table>
<tr>
<td>
<form method="POST" action="pdfdemo.php">
Enter your text here please =>
<input type="text" name="input" size="20" maxlength="20">
<input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset">
</form>
</td>
</tr>
</table>
</body>
</html> |
Create PDF with CPDF
We use the following code to create PDF. Save the following code
as cpdfdemo.php.
<?php
if(isset($_POST['submit'])
{
$mytext=$_POST['
input'];
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, $mytext,
50, 750);
pdf_end_page($pdf);
pdf_close($pdf);
$data = pdf_get_buffer($pdf);
header("Content-type: application/pdf");
header("Content-disposition: inline; filename=test.pdf");
header("Content-length: " . strlen($data));
echo $data;
}
?>
|
$_POST['xxx'] gets parameters from client.
pdf_new(); creates a PDF file.
pdf_open_file($pdf) open a PDF file in memory.
pdf_begin_page sets PDF sizes: A4
is 595 x 842, Letter is 612 x 792 and Legal is 612 x 1008.
pdf_get_buffer reads PDF file into buffer.
pdf_show_xy writes text to a specified location, x=50, y=750 in
this example.
header("Content-type: application/pdf") tells the brower
there is a PDF file.
|