js打印页面

最近项目需要实现将局部页面输出pdf文件,做了以下案例

效果

在这里插入图片描述

html


<template>
    <div id="test-page">
        <!-- 额外元素 -->
        <div class="myInput">
            <el-input v-model="text"></el-input>{{text}}
        </div>
        <!-- 打印按钮 -->
        <el-button @click="printPDF">打印pdf</el-button>
        <!-- 打印元素 -->
        <div id="print-box">
            <div class="fwb">
                测试数据1
                <div v-html="htmlVal"></div>
            </div>
            <div class="fwb">
                测试数据2
                <div v-html="htmlVal"></div>
            </div>
            <div class="fwb">
                测试数据3
                <div v-html="htmlVal"></div>
            </div>
            <div class="fwb">
                测试数据4
                <div v-html="htmlVal"></div>
            </div>
            <div class="fwb">
                测试数据5
                <div v-html="htmlVal"></div>
            </div>
        </div>
    </div>
</template>

js


<script>
export default {
    data() {
        return {
            text:'额外数据',
            htmlVal: '<img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2350171032,3227234175&fm=26&gp=0.jpg" alt="">'
        }
    },
    methods:{
        // 打印pdf
        printPDF(){
            // 获取打印DOM
            let el = document.getElementById("print-box");
            // 当前页面样式
            let headDom = document.getElementsByTagName("head")[0];
            // 创建iframe
            let iframe = document.createElement('iframe');
            // 设置iframe样式
            iframe.setAttribute("id", "print-box");
            iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
            // 在页面插入iframe
            document.body.appendChild(iframe);
            // 获取iframe内的html
            let doc = iframe.contentWindow.document;
            // 经需要打印的DOM插入iframe
            let printMain = document.createElement('div');
            printMain.setAttribute("id", "print-box");
            printMain.innerHTML = el.innerHTML;
            doc.body.appendChild(printMain);
            // 设置iframe内的header,添加样式文件
            doc.getElementsByTagName("head")[0].innerHTML = headDom.innerHTML;
            // 关闭iframe
            doc.close();
            // 使iframe失去焦点
            iframe.contentWindow.focus();  
            // 调用iframe的打印方法
            iframe.contentWindow.print();
            // 移除iframe
            document.body.removeChild(iframe);
        },
    }
}
</script>

style

<style lang="scss" scope>
    #test-page{
        padding: 30px;
    }
    // 要考虑iframe内样式同样生效
    .fwb{
        width: 300px;
        margin: 20px 0;
        border: solid 1px #999;
        padding: 20px;
        box-sizing: border-box;
        font-size: 30px;
        img{
            margin-top: 10px;
            width: 100%;
        }
    }
</style>

注意

设置打印内容时,要考虑样式生效,所以打印区域的样式最好不要放在页面“容器DOM”样式内


版权声明:本文为qq_36939013原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。