简体   繁体   中英

Print txt file using javascript

I would like to know if it is possible to print a txt file located in the server using javascript. I have noticed that window.print() just opens the print dialog for the current web page

You can only open the print dialog for the user, and that is as it should be. If you only want to print the text document, there are a couple ways you can trigger the print dialog for it. They require following the Same Origin Policy (your HTML and TXT files need to be in the same domain).

The simplest way is to open a popup window with the text file, and call print on the window handle returned:

w = window.open('text.txt');
w.print();

If you want the user to preview the text file, you could use an iframe instead:
I recommend keeping JS out of HTML, this is just for example

<iframe id="textfile" src="text.txt"></iframe>
<button onclick="print()">Print</button>
<script type="text/javascript">
function print() {
    var iframe = document.getElementById('textfile');
    iframe.contentWindow.print();
}
</script>

The JQuery option

<body>

    <div id="txtdiv"></div>

    <script type="text/javascript">
      $('#txtdiv').load('trial.txt', function()
      {
        window.print(); //prints when text is loaded
      });

    </script>
 </body>

You are correct that window.print() just opens the print dialog for the current web page.

I would suggest that you write JavaScript code to open a new window, load the text into that window, and then call the print() function on that window.

If you just do not want to delete the contents of the page and print some text from a file, you can do so here:

<body>

....some tags....

<script type="text/javascript">
// or onclick function
$.load('test.txt', function( printContent ){
    history.pushState( printContent, 'Print title', '/print_page' );
    document.write( printContent );
    if( window.print() ){
         document.location = '/back_page/';
         // or history.go(-1);
    } else {
         document.location = '/history/';
    }
});
</script>

You can do this by creating a web service.

  1. Create a web service, and do printing stuff in the webservice.

  2. Call the web service from JavaScript.

If you are wondering how to do printing using webservice there is a thread in stackoverflow which might help. Dont just look the question, browse the answer as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM