前端网页打印指定区域内容

<template>
  <div>
    <!-- 打印内容区域 -->
    <div ref="printContent" class="print-content">
      <h2>打印内容标题</h2>
      <p>这是要打印的内容...</p>
      <table border="1" style="width: 100%">
        <tr>
          <th>项目</th>
          <th>数量</th>
          <th>价格</th>
        </tr>
        <tr>
          <td>商品A</td>
          <td>2</td>
          <td>¥100</td>
        </tr>
        <tr>
          <td>商品B</td>
          <td>1</td>
          <td>¥200</td>
        </tr>
      </table>
    </div>

    <!-- 打印按钮 -->
    <button @click="handlePrint">打印内容</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const printContent = ref(null);

const handlePrint = () => {
  const printWindow = window.open('', '_blank');
  printWindow.document.write(`
    <html>
      <head>
        <title>打印</title>
        <style>
          body { font-family: Arial; margin: 20px; }
          table { border-collapse: collapse; width: 100%; }
          th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
          @media print {
            .no-print { display: none !important; }
            body { margin: 0; padding: 0; }
          }
        </style>
      </head>
      <body>
        ${printContent.value.innerHTML}
        <script>
          setTimeout(() => {
            window.print();
            window.close();
          }, 100);
        <\/script>
      </body>
    </html>
  `);
  printWindow.document.close();
};
</script>

<style scoped>
.print-content {
  margin: 20px;
  padding: 20px;
  border: 1px solid #eee;
}

@media print {
  .no-print {
    display: none !important;
  }
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值