Thursday, June 28, 2007

PHP-Convert any HTML file into PDF

############################################################################
Function to Convert any HTML file into PDF
Can save into a pdf file on server, or stream to the user's browser
If you want to stream to the browser: $objClass->fnURL2PDF("http://www.yahoo.com", "pdf.pdf");
If you want to save on the server: $objClass->fnURL2PDF("http://www.yahoo.com", "", "../folder/filename.pdf");
Usage: $objClass->fnURL2PDF("http://www.yahoo.com", "pdf.pdf"); Default is USA
############################################################################
function fnURL2PDF($varURL, $varFileName = "pdf.pdf", $varSavePath = "")
{
$varSocket = fsockopen("www.easysw.com", 80, $errno, $errstr, 1000);
if (!$varSocket) die("$errstr ($errno)\n");

fwrite($varSocket, "GET /htmldoc/pdf-o-matic.php?URL=" . $varURL . "&FORMAT=.pdf HTTP/1.0\r\n");
fwrite($varSocket, "Host: www.easysw.com\r\n");
fwrite($varSocket, "Referer: http://www.easysw.com/htmldoc/pdf-o-matic.php\r\n");
fwrite($varSocket, "\r\n");

$varHeaders = "";
while ($varStr = trim(fgets($varSocket, 4096)))
$varHeaders .= "$varStr\n";

$varBody = "";
while (!feof($varSocket))
$varBody .= fgets($varSocket, 4096);

if ($varSavePath != '')
{
// Save the File
$varFileHandle = @fopen($varSavePath,'w');
$varBytes = @fwrite($varFileHandle, $varBody);
}
else
{
//Download file
if(isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']) and strpos($HTTP_SERVER_VARS['HTTP_USER_AGENT'],'MSIE'))
Header('Content-Type: application/force-download');
else
Header('Content-Type: application/octet-stream');
if(headers_sent())
die('Some data has already been output to browser, can\'t send PDF file');
Header('Content-Length: '.strlen($varBody));
Header('Content-disposition: attachment; filename='.$varFileName);
echo $varBody;
}
return(true);
}


Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

No comments: