Wednesday 13 January 2016

How to Print or Save as PDF Particular Div Element Data By Using JS, Css and HTML

It is possible to provide print facility for particular Div of your HTML file. To Do this follow  below instructions.

Step 1: Give an Unique Id to your HTML Div element whose data you want to Print or want to save as PDF.

Step 2: If your Div Element is not  simple plain text, It contains colors, font styles, borders, margins, padding etc. please use External CSS* file instead of Inline Css or Embedded Css.

Step 3: Now you need to load any version of JQuery, Here in this example i am using JQuery for the purpose of write less Do more. their is no dependency on JQuery to Print Div Element. To add JQuery add below script in you HTML Page.

<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"> </script>
  Step 4:  Now Add Below Javascript Code at the end of your HTML.

<script type="text/javascript">
$(function () {
$("#PrintButtonID").click(function () {
var contents = $("#DivIDToBePrint").html();
var frame1 = $('<iframe />');
frame1[0].name = "frame1";
frame1.css({ "position": "absolute", "top": "-1000000px" });
$("body").append(frame1);
var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
frameDoc.document.open();
//Create a new HTML document.
frameDoc.document.write('<html><head><title>AM info System</title>');
frameDoc.document.write('</head><body>');
//Append the external CSS file.
frameDoc.document.write('<link href="style.css" rel="stylesheet" type="text/css" />');
//Append the DIV contents.
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
frame1.remove();
}, 500);
});
});
</script>
Download Working Example from here
 

No comments:

Post a Comment