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
-
It is not possible with only javascript. You should use also ajax with or without some server scripting language.Rafael Sedrakyan– Rafael Sedrakyan2012-06-27 14:21:28 +00:00Commented Jun 27, 2012 at 14:21
-
2You can't force someone to print a page if they don't want to. The print dialog is how users decide how to print something, or decide if they don't actually want to print anything.zzzzBov– zzzzBov2012-06-27 14:56:23 +00:00Commented Jun 27, 2012 at 14:56
5 Answers
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>
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>
Comments
You can do this by creating a web service.
Create a web service, and do printing stuff in the webservice.
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.