How to Print Page Area using JavaScript

Generally, the browser’s print option is used to print webpage content. In this case, the entire page content is selected to print on the browser. The browser print dialog does not allow to select a specific section of the webpage for printing. We need to get the help of the client-side or server-side code to print specific areas of the web page.

The print feature in the web application allows users to print the content of the webpage for offline use. There are various jQuery plugins are available to print web page content. If you don’t want to use any third-party plugins, this functionality can be implemented easily with JavaScript. You can print specific area or full-page HTML content using JavaScript.

In this tutorial, we will show you how to print specific div content or full-page content using JavaScript. For better usability and to make the process user-friendly, we will create a custom JavaScript function to print div content, page area, and full web page content.

Print HTML Content using JavaScript

The printPageArea() function contains some JavaScript code that helps you to implement the print feature easily on the web page. It will provide the simplest way to print specific areas of the web page.

JavaScript Code:
The printPageArea() function will open a print dialog window with web page content and printing option based on the provided element ID. You can use this function to print a specific area of a web page or full web page content.

function printPageArea(areaID){
    var printContent = document.getElementById(areaID).innerHTML;
    var originalContent = document.body.innerHTML;
    document.body.innerHTML = printContent;
    window.print();
    document.body.innerHTML = originalContent;
}

Use the printPageArea() function on onclick event of the print button element and provide the content area div ID which you want to print.

printPageArea('elementID')

HTML Code:

Define the HTML button element that will trigger the code>printPageArea() function to initialize the printing code in JavaScript.

<a href="javascript:void(0);" onclick="printPageArea('printableArea')">Print</a>

Specify the HTML content to be printed.

<div id="printableArea">
    All the printable content goes here...
</div>

Print Dynamic Content using JavaScript and PHP

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

2 Comments

  1. Sanjay Said...
  2. Emad Said...

Leave a reply

keyboard_double_arrow_up