window.print() 实现A4纸张打图片分页,解决预览首页空白页、打印多出一张空白页问题

注意

<!--startprint-->
<!--endprint-->

把打印的内容放到这个标签里面

<div class="layui-row" style="background-color: #FFFFFF;">
        <a class="layui-btn" onclick="preview();" style="margin-bottom: 5px;">打印</a>
    <a type="reset" id="goBack" class="layui-btn layui-btn-primary" onclick="JavaScript:history.go(-1);" style="margin-bottom: 5px;">返回</a>
        <div style="width: 1000px;">
            <!--startprint-->
            @if(count($contract))
                @foreach($contract as $key=>$value)
                    <img src="{{asset('public/upload').'/'.$value}}" style="width: 100%;height: 1000px;">
                @endforeach
            @endif
            <!--endprint-->
        </div>
    </div>

 下面是点击打印触发的方法:

注意:如果出现一张图片分到两个页面上,一定要调整img标签的height属性,微调至不分页

<script>
    function preview()
    {
        bdhtml=window.document.body.innerHTML;//获取当前页的html代码
        sprnstr="<!--startprint-->";//设置打印开始区域
        eprnstr="<!--endprint-->";//设置打印结束区域
        prnhtml=bdhtml.substring(bdhtml.indexOf(sprnstr)+18); //从开始代码向后取html
        prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));//从结束代码向前取html
        window.document.body.innerHTML=prnhtml;
        window.print();
        window.document.body.innerHTML=bdhtml;
    }
<script>

也是参考了https://blog.csdn.net/fmwind/article/details/86841183


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