首页 > 解决方案 > HTML textarea 行数

问题描述

我目前有一个 html 文本区域,可以在按下按钮时保存到文本文件(使用 javascript)

这很好用,但我被告知他们现在需要页码和页总数,如果可能的话,还需要每页上的页眉。如果我可以计算出打印的 A4 页面的总行号,那么我可以为每第 n 行插入一个标题。

这是我当前使用的 javascript 代码。

 function saveTextAsFile()
{
    var textToWrite = "School Centre Number: " + document.getElementById("centernumber").value + "\nStudent Name:" + document.getElementById("studentname").value + "\r\n" + "Date and Time: " + document.getElementById("date").value+" " + document.getElementById("time").value+ "\r\n"+ "Exam Title: "+ document.getElementById("examtitle").value+ "\r\n\r\n"+document.getElementById("inputText").value;
    textToWrite = textToWrite.replace(/\n/g, "\r\n"); 

var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});

    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }
    downloadLink.click();
}

感谢您的任何反馈

ps 最好不要使用 html 和 javascript 的外部库

标签: javascripthtmltextsave

解决方案


用了这个方法

https://stackoverflow.com/a/45252132/7805456

与新行、回车和换行文本完美、准确地配合使用。


推荐阅读