我正在尝试从服务器的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
当我单击加载按钮时,文本按原样加载,但是当我尝试打印时,该文本显示为乱码,如下图所示:
有人可以告诉我我做错了什么吗?谢谢
答案 0 :(得分:2)
丢失格式的文本是因为打开弹出窗口时,您将添加不带“ pre”标签的文本,这些标签将保留格式的方面。
您只需要在弹出窗口中附加“ pre”标签即可:
printwindow.document.write('</head><body ><pre>');
printwindow.document.write(id.textContent);
printwindow.document.write('</pre></body></html>');
答案 1 :(得分:1)
<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>