Printing HTML with JavaScript
Published on: 2nd Nov 2017
Updated on: 10th Jan 2022
Overview
Let says you want to allow the user from printing current page directly to the printer and it is going to be a bit complex for the first time to do this.
The printing components
-
Add a print button onto the HTML page that calls your print function (written in JavaScript).
-
In your print function, you need to do the following thing:
1.1. Inject a hidden iframe.
1.1. Set the src
to the page that you have to print. If you are developing a POS (Point of Sales), you may specify the URL of the receipt page to the src
together with the receipt number in the query string. For example,
<iframe id="receipt-frame" style="display:none;" src="myReceipt.aspx?refno=123456"/>
Note: the page that you call should return the contents to be printed out. You have two choices to merge the data into the receipt format: (1) do everything at the server side (2) execute client side JavaScript upon page loaded.
1.1. Once you have the content to be printed, you need to call the following function (upon page loaded). This function will send the content to the printer.
window.onafterprint = function() {
window.parent.myPrintJobCompleted();
}
window.print();
In case you want to inform the parent page that the user has printed the content, you must handle the window.onafterprint
event. In the example above, it executes the function myPrintJobCompleted (this function will load with the main page). Please take note that onafterprint
will be triggered upon the HTML has been loaded into the iframe which is not the actual printing at the printer.
Conclusion
With the above code, you will be able to have printing feature in your web application easily.
Jump to #JAVASCRIPT blog
Author
Lau Hon Wan, software developer.