[英]Print the contents of a text file using javascript/jquery
我的系統中有一個文本文件。 我想使用javascript / jquery打印該文本文件的內容。 我怎樣才能做到這一點。 我已經提到了鏈接 。 但這只是從div打印而已。 我需要使用window.print()
方法。 但是如何使用javascript打印文本文件? 請指導我。
首先打開文本文件並打印。
var w = window.open('yourfile.txt'); //Required full file path.
w.print();
小提琴示例: https : //jsfiddle.net/shree/91459gm9/
Fiddle沒有找到文件,但是找到了打開的示例文件和要打印的打印窗口。
使用該代碼可以解決您的問題:
<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>
我認為您需要后端(php,rails,nodejs)支持以從計算機讀取文件,然后將其顯示在任何HTML塊上,然后進行打印,這是打印文件的最佳方法
如果您具有后端設置,並且文件必須在服務器上,則可以使用以下語法
$(document).ready(function(){
$("button").click(function () {
$.ajax({
url : "Content.txt",
dataType: "text",
success : function (result) {
$("#container").html(result);
}
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.