Print content from a particular div element using jQuery

By Faruque Ahamed Mollick

Here in this post, we are going to see how to print content from a particular div element using jQuery so that it can be saved as PDF.

In this tutorial, we are going to use printThis jquery plugin. To follow this tutorial download the JavaScript file from the GitHub project. From there just get the printThis.js.

Now I am going to tell you how to use printThis.js jQuery plugin.

jQuery multiple events to trigger same function

Generate PDF from HTML template in PHP using Dompdf

Using the printThis plugin is very easy. Below is the given code for basic usage of this plugin:

$('selector').printThis();

The above JavaScript code will exactly print the content inside the selector or element. Just provide the element in the above code and it will print the content from the element.

There are also advanced features available in this plugin. Below is the code which is using the advanced feature of this plugin:

$('selector-one, selector-two, selector-three').printThis({
    importCSS: false,
    loadCSS: "",
    header: "<h1>This is the heading for the PDF</h1>"
});

So you have seen that how easy is it to use this plugin. You just need to write few lines of code which will do that very easily.

Now below is a complete HTML file which shows the basic usage of this plugin:

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <!--<script src="https://unpkg.com/[email protected]/dist/jspdf.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="printThis.js"></script>

</head>
<body>

<h2 id="content-to-print">This is the content which will be print</h2>
<button id="print-element">Print the aboive content</button>

<h2>This is the content which will not be print</h2>

<script type="text/javascript">
  $( "#print-element" ).click(function() {
       $("#content-to-print").printThis();
    });
</script>

</body>
</html>

In the above code, we have created a button and using the jQuery click method we have set an onClick event. When the button will be clicked, it will print a content inside the specified element. To better understand, we can see two h2 heading tag. One h2 tag will be available in the print window. But the other will not be print and will not be available inside the PDF.

Thus we can understand that it is printing only the specific div element.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *