30

So, lets say I got a simple form inside a page like this:

<form style="text-align:center;">
    <p> STUFF </p>
</form>

I wanna add a button so when the user clicks on it the browser's Print dialog shows up, how can I do that?

Edit: I wanna print the form, not the page.

ataravati
  • 8,656
  • 6
  • 51
  • 80
user2962142
  • 1,646
  • 5
  • 26
  • 38

4 Answers4

56

Print the whole page

Try adding a button that calls window.print()

<input type="button" value="Print this page" onClick="window.print()">

Print a specific portion/container in a page

<div id="print-content">
 <form>

  <input type="button" onclick="printDiv('print-content')" value="print a div!"/>
</form>
</div>

then in the HTML file, add this script code

<script type="text/javascript">
    function printDiv(divName) {
        var printContents = document.getElementById(divName).innerHTML;
        w=window.open();
        w.document.write(printContents);
        w.print();
        w.close();
    }
</script>

Refer Print <div id="printarea"></div> only?

Minasie Shibeshi
  • 350
  • 2
  • 16
Murali Murugesan
  • 21,923
  • 17
  • 67
  • 118
3

To print with submit button, add this to your summit script:

<input type="button" value="Print this page" onClick="window.print()">

Keep in mind, this will only trigger whatever browser implemented print capabilities are available at the client.

cocogorilla
  • 1,775
  • 12
  • 36
Vin
  • 31
  • 1
1

What you need is the window.print():

<form style="text-align:center;">

  <p> STUFF </p>

  <a href="#" id="lnkPrint">Print</a>
</form>

Javascript:

$( document ).ready(function() {
    $('#lnkPrint').click(function()
     {
         window.print();
     });
});
Cloud SME
  • 10,111
  • 3
  • 51
  • 90
0

As well as the above there are a couple of other approches you can take here:

<a href="Javascript:window.print();">Print</a>

and to not include any JS in your HTML:

const el = document.getElementById("aTag");
el.addEventListener("click", () => { window.print();});
<a id="aTag">print</a>
Liam
  • 25,247
  • 27
  • 110
  • 174