Thursday, 2 November 2017

Printing HTML with JavaScript

You want to allow the user from printing current page directly to the printer and here is the recipe:


1. A print button that calls your print function (written in JavaScript).

2. In your print function, you need to do the following thing:

2.1. Inject a hidden iFrame.

2.2. 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.

2.3. 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).

No comments:

Post a Comment

We are moving

We are moving this blog to our new blog site: https://ciysys.com/blog/nodejs.htm