Adding "Download PDF" button to a webpage

Adding a "Download PDF" button on a webpage can give the user an option to print only a certain section of your webpage in PDF format. This feature is of great use if your website is used to generate a report. That report (or anything else) can be placed inside a DIV and then a "Download PDF" or "Print PDF" button can be added into it to download contents of that particular DIV. Usually a website/webpage contain a lot of content, such as sidebars and related posts, in which user might not be interested in printing.

Without wasting any time lets show you the javascript and HTML code.

The code will be implemented in two parts: HTML and Javascript.

HTML Part

<div id="printableArea"> <h1>Print me</h1> </div> <input type="button" onclick="printDiv('printableArea')" value="Save as PDF or Print" />

In the above code you may change id of div as per your need to print only a particular div.

Javascript Part

<script type="text/javascript"> // Author : Prixit Parashar // Website : bestrix.blogspot.com function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script>

Note: This button opens the simple printing interface, from where you can either choose to print by selecting a printer or saving the preview content as PDF.

This button is a working example of the code given above. It can be used to print this article only, not the entire content of this page.
Share this Article :
Email

No comments:

Post a Comment