PD4ML is HTML-to-PDF converting Java library, but with a simple
wrapper application it works also in PHP environment. The
application expects there is Java runtime environment 1.4 (or above)
installed on the server.
Below is a sample implementation of "As PDF" button, which can add to
any PHP page its PDF view.
First we need a small Java application, which accepts a document URL as a
parameter and outputs the resulting PDF to STDOUT.
Download the application in source and in
compiled form.
The Java code utilizes only basic features
of PD4ML, but it could be easily extended. See PD4ML
reference.
The next step is to create a converter PHP
(let's call it pd4ml.php).
<?
if ($_SERVER["HTTPS"] != "on") {
// MS IE needs to cache PDF obtained by HTTPS.
header('Pragma: no-cache');
header('Expires: -10000');
}
// Windows version
//passthru('java -Xmx512m -cp .;pd4ml_demo.jar Pd4Php ' . $_POST['url']
. ' 800 A4');
} else {
echo 'invalid usage';
}
?>
The converter PHP expects the source
URL is passed as an HTML form variable named 'url'.
OK, the last step is to create the button.
<?php
// the function determines the current page URL
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .=
"localhost:".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= "localhost".$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
<!-- ... your HTML code here ... -->
<!-- the button -->
<form action="pd4ml.php" method=post>
<input type=hidden value="<?php echo curPageURL(); ?>" name=url>
<input style="pd4ml-display: none; pd4ml-visibility: hidden"
type=submit
value="Get the invoice as PDF">
</form>
PD4ML-specific style="pd4ml-display: none; pd4ml-visibility: hidden" excludes
the button from the resulting PDF layout.
If you deploy the application to a server, which hosts multiple web sites,
"localhost" server address cannot be distinct. Please use your actual server
name in
curPageURL()instead of it.
In order to deploy the PDF generating solution you need to copy pd4ml.jar (or
pd4ml_demo.jar) and ss_css2.jar from PD4ML distribution, the wrapper class
Pd4Php.class and pd4ml.php file to any PHP-enabled directory of your web server.
Please also make sure that your PHP engine is not in safe mode, which
disables passthru() calls (can be checked with
<?php phpinfo()?>).
Download all the files mentioned in the
article and a demo invoice PHP (index.php), convertable to PDF.