Print txt file using javascript

喜欢而已 提交于 2021-01-23 04:50:08

问题


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


回答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>



回答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>



回答3:


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.




回答4:


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>




回答5:


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.



来源:https://stackoverflow.com/questions/11228280/print-txt-file-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!