How to Print Page Area using JavaScript


how-to-print-page-area-using-javascript-by-codexworld

Print web page content is a commonly used feature in the web project. You can find many jQuery Plugin to print specific area or full page. This article provides a simple way to print specific div content or full page content using JavaScript. Here we’ll create a JavaScript function to print div content, page area, and full web page content.

printPageArea() function contains some JavaScript code which helps you to implement print feature easily in the web page. It will provide the simplest way to print specific area of web page.

JavaScript Code:

printPageArea() function opens a new window with web page content and printing option based on the provided element ID. You can use this function for print a specific area of web page or full web page content.

function printPageArea(areaID){
    var printContent = document.getElementById(areaID);
    var WinPrint = window.open('', '', 'width=900,height=650');
    WinPrint.document.write(printContent.innerHTML);
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
}

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

printPageArea('elementID')

HTML Code:

The print button which will trigger printPageArea() function on clicking on it.

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

HTML content which needs to be printed.

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

Leave a reply

Connect With CodexWorld