js逻辑_浏览器打印window.print

打印方法

 window.print()

print() 方法用于打印当前窗口的内容, 默认情况下会将整个html页面 的内容转换为pdf ==> 支持在线预览打印或者导出pdf。

以下是打开百度页面 在控制台调用 window.print 方法 后弹出的弹框 ,在右侧可以选择 纵向/横向打印。
需要注意的是: 页眉和页脚是 在打印时自带的, 无法去掉!
在这里插入图片描述
也就是说,若是我们想打印某部分数据,需要先准备一个盒子,等待打印时,将这个盒子的内容赋值给document进行打印。

  • [1]内容区域
      <div id='print'>
        <!-- 打印内容-->
      </div>
    
  • [2] 打印
    const printHTML = document.querySelector('#print').innerHTML
    window.document.body.innerHTML = printHTML
    window.print()
    // 打印完成后重新加载页面
    window.location.reload() 
    

监听打印事件

  • beforeprint: 打印开始时被触发
  • afterprint:打印结束时被触发
  • 举例说明
      window.addEventListener('beforeprint', () => {
          
          
       console.log('打印开始')
      })
    
      window.addEventListener('afterprint', () => {
          
          
          console.log('打印结束')
      })
    

常用逻辑

[1]打印数据为表格

当需要打印的数据是表格是,建议使用原生html的table标签而不是组件表格。

因为组件样式在打印时可能不显示!

  <!--
    border="1" 边框
    cellspacing="0" 边框间间距为0
    设置line-height调整单元格高度

    table  表格
      thead  表格头
        tr  表格行
        th  标题单元格
      tbody  表格内容
        tr  表格行
        td  表格单元格
  -->
  <table border="1" cellspacing="0" style="border: 1px solid #bfbdbd; font-size: 12px; line-height: 32px">
    <thead>
      <!--字体和宽度与其他表格行不一致的单独处理-->
      <tr>
        <th style="text-align:center;font-size:24px; line-height: 48px; height: 48px;">
          罚单退款申请单
        </th>
      </tr>
      <tr >
        <th width="50">序号</th>
        <th width="150">订单ID</th>
        <th width="150">罚单编号</th>
        <th width="100">支付总计(元)</th>
        <th width="120">支付渠道</th>
        ...
      </tr>
    </thead>
    <tbody>
      <tr v-for="item, key in totalTableData">
         <td>{
   
   { item.order_id }}</td>
         <td>{
   
   { item.paid_total_fee }}</td>
         ....
      </tr>
    </tbody>
  </table>

强制换行

如上示例中,在设置一列时给每一列设置了宽度,但是若是宽度超过总宽度则会对每列宽度进行等比压缩,若是单元格内容是文本则会自动换行,但是若是数字则会覆盖另一单元格的文本,因此需要设置强制换行。

 <td  style="word-wrap: break-word;">{
   
   {item.id}}</td>

猜你喜欢

转载自blog.csdn.net/qq_43260366/article/details/129756232