Categories
Tips

Print PDF files with JavaScript/PHP

I started a topic in DaniWeb about how to generate a gadget to let customer choose from a list of pdf files an create a custom order form from them… I still working on it but here is something I found that will help many of your that are looking for a solution how to print a pdf file with JavaScript. After a lot of googling I finally find some pieces of codes that will help you to complete this task, you can use only JavaScript or you can combine PHP/JavaScript to do it.

But here i will show you with both programming languages interacting together…. For this task we need to request the browser information in order to decipher which code to use with Internet Explorer and which to use for the rest of them…

<?php

$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];

if ($browser_ver['browser'] == 'IE') {
?>

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
html { height:100%; }
</style>
<script>
function printIt(id){
var pdf = document.getElementById("samplePDF");
pdf.click();
pdf.setActive();
pdf.focus();
pdf.print();
}
</script>
</head>

<body style="margin:0; height:100%;">

<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" onLoad="printIt('samplePDF');" />
<button onClick="printIt('')">Print</button>

</body>
</html>

<?php
} else {
?>
<HTML>
<script Language="javascript">

function printfile() {
    window.frames['objAdobePrint'].focus();
    window.frames['objAdobePrint'].print();
}

</script>
<BODY marginheight="0" marginwidth="0">

<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe>

<input type="button" value="Print" onclick="javascript: printfile();">

</BODY>
</HTML>
<?php
}
?>

As you see there’s a big difference between the most used browsers (IE 13.5%), (Firefox 29.6%) and (Chrome 50%) so the sad reality that we need to code for all of them. But with the new IE 10, coding it is a bit more easier. This little piece of code might help anyone.

I hope so. I spent all my day searching for solutions for a mayor project. At least this is a big step into it.

Happy Coding

Leave a Reply