在JavaScript打印文本文件

问题描述 投票:0回答:2

我试图加载的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按钮,文本被加载,因为它是,但是当我尝试打印,它是乱码,如下面的图片:enter image description here

有人能告诉我什么,我做错了什么?谢谢

javascript html5 printing
2个回答
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>

2
投票

你失去格式化文本,因为当您打开弹出,你没有追加“预”标记文本,该文本保持格式化方面。

您只需将“预”标记在弹出:

printwindow.document.write('</head><body ><pre>');
printwindow.document.write(id.textContent);
printwindow.document.write('</pre></body></html>');
© www.soinside.com 2019 - 2024. All rights reserved.