我试图加载的HTML页面,从服务器的文本文件,并打印内容。该文本文件有特定的格式,所以我不能改变它。下面是我的示例代码:
<html>
<head>
<title>Print test</title>
<script>
var url = './text.txt';
function load() {
fetch(url).then(function(resp) {
resp.text().then(function(text) {
var id = document.getElementById("abc");
id.textContent = text;
});
});
}
function print() {
var id = document.getElementById("abc");
var printwindow = window.open('', 'PRINT', 'height=400,width=600');
printwindow.document.write('</head><body >');
printwindow.document.write(id.textContent);
printwindow.document.write('</body></html>');
printwindow.document.close(); // necessary for IE >= 10
printwindow.focus(); // necessary for IE >= 10
printwindow.print();
printwindow.close();
}
</script>
</head>
<body>
<pre id="abc" style="height:85%;overflow:auto; background:white">
</pre>
<button onclick="load()">Load</button>
<button onclick="print()">Print</button>
</body>
示例文本文件是以下几点:
的text.txt
NAME = ABC
SURNAME = CDE
OCCUPATION = XYZ
PLACE = UUU
当我点击Load按钮,文本被加载,因为它是,但是当我尝试打印,它是乱码,如下面的图片:
有人能告诉我什么,我做错了什么?谢谢
<html>
<head>
<title>Print test</title>
<script>
var url = './text.txt';
function load() {
fetch(url).then(function (resp) {
resp.text().then(function (text) {
var id = document.getElementById("abc");
id.textContent = text;
});
});
}
function print() {
var id = document.getElementById("abc");
var printwindow = window.open('', 'PRINT', 'height=400,width=600');
printwindow.document.write('</head><body >');
printwindow.document.write("<pre>" + id.textContent + "</pre>");
printwindow.document.write('</body></html>');
printwindow.document.close(); // necessary for IE >= 10
printwindow.focus(); // necessary for IE >= 10
printwindow.print();
printwindow.close();
}
</script>
</head>
<body>
<pre id="abc" style="height:85%;overflow:auto; background:white">
</pre>
<button onclick="load()">Load</button>
<button onclick="print()">Print</button>
</body>
</html>
你失去格式化文本,因为当您打开弹出,你没有追加“预”标记文本,该文本保持格式化方面。
您只需将“预”标记在弹出:
printwindow.document.write('</head><body ><pre>');
printwindow.document.write(id.textContent);
printwindow.document.write('</pre></body></html>');