How to easily print div using jquery


Hi folks, today we are going to see how to dynamically print div using jquery and generate a pdf out of it. You might have come across some sites that tell you to print invoices, calendars, cards and so on, and probably you wondered how they achieved that. Am going to share my code as well as share all the files included under this tutorial

1. How to print div using jquery

Before we proceed with this project, all the project files can be found in the download page and you can directly download them here (zip 36.0KB). To achieve our desired output we shall be using a jquery library, called jquery.print, you will see it in the project files.

2. Programming on how to print div using jquery

For this system to function, you will need two jquery files; jquery.js and Jquery.print.js, there will be no need to download them since they have been provided in the project files. The following is the code on how to print div in jquery.



<html>
<head>
	<title>Printind dive using jquery</title>

	<script src='jquery.js'></script>
	<script src="jQuery.print.js"></script>
	<script>
		// here we will write our custom code for printing our div
		$(function(){
			$('#print').on('click', function() {
                //Print ele2 with default options
                $.print(".print_div");
            });
		});
	</script>
</head>
<body style='background: #f9f9f9'>

	<div class='print_div' style="border: 1px solid #a1a1a1; width: 300px; background: white; padding: 10px; margin: 0 auto; text-align: center;">
		<h4>HACK SMILE TUTORIALS</h4> 
		thanks for choosing hacksmile to teach you important programming concepts
	</div>
	<center><button id='print' style='margin-top: 10px; padding: 10px; border: none; text-align: center; background: black; border-radius: 4px; color: #fff; font-weight: bold; cursor: pointer;'>PRINT ABOVE DIV</button></center>

</body>
</html>

Conclusion

Feel free to test this system. In case you need any clarification, please ask in the commenting system below, I will reply within hours. Also, if it worked for you, you can leave cheers message in the commenting system below. Thanks