How does the Javascript print function work? Can I create a document using javascript and print it off?

后端 未结 8 1582
梦毁少年i
梦毁少年i 2021-02-09 07:17

I know you can use window.print() to print the current page... but what I want to know is can I build a document using javascript in order to populate it with data and print it

相关标签:
8条回答
  • 2021-02-09 07:51

    There is a simple solution available no need to write a function and that is - window.print()

    whereever you want to use it just put - onClick="window.print();"

    Example

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

    I testes it every browser and it works like a charm !

    0 讨论(0)
  • 2021-02-09 07:55

    My first thought:

    You could create an iframe programmatically, assign the HTML to be printed, call the print() function on the context of the iframe.contentWindow, and then remove the iframe from the DOM:

    function printHTML(input){
      var iframe = document.createElement("iframe"); // create the element
      document.body.appendChild(iframe);  // insert the element to the DOM 
    
      iframe.contentWindow.document.write(input); // write the HTML to be printed
      iframe.contentWindow.print();  // print it
      document.body.removeChild(iframe); // remove the iframe from the DOM
    }
    
    printHTML('<h1>Test!</h1>');
    

    You can test the above snippet here.

    0 讨论(0)
提交回复
热议问题