Auto start print html page using javascript

147,213

Solution 1

<body onload="window.print()"> or window.onload = function() { window.print(); }

Solution 2

The following code must be put at the end of your HTML file so that once the content has loaded, the script will be executed and the window will print.

<script type="text/javascript">
<!--
window.print();
//-->
</script>

Solution 3

Add the following code in your HTML page, and it will show print preview on page load.

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<script type="text/javascript">

$(document).ready(function () {
    window.print();
});

</script>

Solution 4

Use this script

 <script type="text/javascript">
      window.onload = function() { window.print(); }
 </script>

Solution 5

If what you want is to open a separate window from the web browser you can use this:

  window.open(basePath + "Controller/Route/?ID=" + param, '_blank').print();
Share:
147,213
fmsf
Author by

fmsf

CEO / CTO at https://temploescondido.pt/ Engineer at Palantir

Updated on July 24, 2022

Comments

  • fmsf
    fmsf almost 2 years

    Is there anyway to automatically run javascript:window.print() when the page finishes loading?

  • Deva
    Deva over 15 years
    The second variation is the preferred method.
  • Spudley
    Spudley about 12 years
    better to use <script type="text/javascript"> rather than using the deprecated language attribute.
  • fmsf
    fmsf about 12 years
    If that's not in the end of the HTML it will start the printing process before the page is loaded.
  • elipoultorak
    elipoultorak over 8 years
    Why not window.onload = window.print;
  • jave.web
    jave.web over 5 years
    @elipoultorak not this case specifically, but some calls for native functions that are not direct are causing "Illegal invocation" error, so this is generally discouraged so not used as much :)