JS 创建网页直接打印

主要精华
var printWindow = window.open(”, ‘_blank’);

printWindow.document.write(e);

printWindow.document.close();

printWindow.print();

下面是范例代码

function cx(l_1,l_2,l_3,l_4,l_5,l_6){
        let e="XXXXXXXXXXXXXXXXXXXXXXXXX</body></html>"
//e中放入html文字,需要替换的{1}{2}{3}等等用于替换
        console.log(123)
        e=e.replace(/\{1\}/g, l_1)
        e=e.replace(/\{2\}/g, l_2)
        e=e.replace(/\{3\}/g, l_3)
        e=e.replace(/\{4\}/g, l_4)
        e=e.replace(/\{5\}/g, l_5)
        e=e.replace(/\{6\}/g, l_6)
        // console.log(e)

//打印的精华功能
        var printWindow = window.open('', '_blank');
        printWindow.document.write(e);
        printWindow.document.close();
        printWindow.print();
    }

function get_info(){
//爬取网页信息,可以不使用
    var l_1=document.getElementById("htcfbmId$text").value
    var l_2=document.getElementById("htbh$text").value
    var l_3=document.getElementById("htmc$text").value
    var l_4=document.getElementById("jine$text").value
    if(l_4=='0'){
        l_4="------"
    }else{
        l_4=l_4+".00元"
    }
    var mx=document.querySelectorAll("[name='dfdwId']")
    var l_5=''
    mx.forEach(element => {
        l_5=l_5+"\n"+element.previousElementSibling.querySelector('input').value
    });
    var l_6=document.getElementById("deptName$text").value
    cx(l_1,l_2,l_3,l_4,l_5,l_6)
}

function create_btn(){
//创建按钮
    var button = document.createElement('button');
    button.innerHTML = '打印申请表';
    button.style.position = 'fixed'; // 固定定位
    button.style.top = '10px';       // 距离顶部10px
    button.style.right = '200px';     // 距离右侧10px
    button.style.padding = '10px 20px'; // 内边距
    button.style.backgroundColor = 'blue'; // 背景颜色
    button.style.color = 'white';    // 文本颜色
    button.style.border = 'none';    // 无边框
    button.style.borderRadius = '5px'; // 圆角
    button.style.cursor = 'pointer'; // 鼠标指针样式
    button.style.zIndex = '9999';    // 确保按钮在最上层
    button.onclick = function() {
        get_info();
    };
    document.body.appendChild(button);

}

create_btn();

发表回复