Reputation: 1726
I have a text file in my system. I want print the contents of that text file using javascript/jquery. How can I do that. I have referred the Link. But it is simply printing from div. I need to use window.print()
method. But how can I print the text file using javascript? Please guide me.
Upvotes: 0
Views: 17305
Reputation: 3531
i think you need back-end (php,rails,nodejs) support for reading file from computer and then display it on any HTML Block then Print this is most preferable way to print a file
you can use below syntax if you have back-end setup and file must be on your server
$(document).ready(function () {
$("button").click(function () {
$.ajax({
url : "Content.txt",
dataType: "text",
success : function (result) {
$("#container").html(result);
}
});
});
});
Upvotes: 0
Reputation: 22323
First open text file and print.
var w = window.open('yourfile.txt'); //Required full file path.
w.print();
Fiddle sample : https://jsfiddle.net/shree/91459gm9/
Fiddle don't found file but its open sample file and print window to print.
Upvotes: 3
Reputation: 424
Use that code may solve your problem:-
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script>
<script type="text/javascript">
function PrintElem(event)
{
var selectedFile = event.target.files[0];
var reader = new FileReader();
var result = document.getElementById("mydiv");
reader.onload = function(event) {
result.innerHTML = event.target.result;
};
reader.readAsText(selectedFile);
console.log(selectedFile);
//Popup($('#mydiv').html());
}
function Popup(elam)
{
//console.log($(elam).html());return false;
var data = $(elam).html();
var mywindow = window.open('', 'my div', 'height=400,width=600');
mywindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
mywindow.document.write('</head><body >');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.print();
mywindow.close();
return true;
}
</script>
</head>
<body>
<div id="mydiv">
</div>
<input type="file" onchange="PrintElem(event)">
<input type="button" value="Print Div" onclick="Popup('#mydiv')" />
</body>
</html>
Upvotes: 0