Print txt file using javascript

46,702

Solution 1

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>

Solution 2

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>

Solution 3

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>

Solution 4

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.

Share:
46,702
Admin
Author by

Admin

Updated on February 09, 2020

Comments

  • Admin
    Admin over 4 years

    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

  • sv_in
    sv_in about 12 years
    In his question, he is saying that he wants the file to be printed not just show the print dialog.
  • zzzzBov
    zzzzBov about 12 years
    @sv_in, you're right, i forgot to add the disclaimer that you can't force a user to print something they don't want to.