当前位置: 首页 > news >正文

Vue3 打印网页内容

<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>

使用 CSS 媒体查询隐藏非打印内容

<template><div><!-- 不打印的内容 --><div class="no-print"><h1>网页标题</h1><nav>导航菜单...</nav></div><!-- 打印内容 --><div class="printable-area"><h2>订单详情</h2><p>订单号: 123456789</p><!-- 更多打印内容... --></div><button @click="printPage" class="no-print">打印页面</button></div>
</template><script setup>
const printPage = () => {window.print();
};
</script><style>
/* 普通样式 */
.no-print {padding: 20px;background-color: #f5f5f5;
}.printable-area {padding: 20px;margin: 20px 0;border: 1px dashed #ccc;
}/* 打印样式 */
@media print {.no-print {display: none;}.printable-area {border: none;padding: 0;margin: 0;}body {font-size: 12pt;line-height: 1.5;}
}
</style>

相关文章:

  • JavaScript解密实战指南:从基础到进阶技巧
  • Python多任务编程:进程全面详解与实战指南
  • Linux教程-Shell编程系列二
  • 集合框架拓展--stream流的使用
  • 生成式AI对话中提示词策略:明确问题、明确目标和提供背景信息是最有效的策略
  • 一招解决所以Maven找不到依赖包的问题
  • Java优雅实现判空方法
  • 在 QCustomPlot中自定义绘图元素
  • 【CentOs】构建云服务器部署环境
  • ClickHouse核心架构设计
  • day47——平方数之和(LeetCode-633)
  • STM32(M4)入门:GPIO与位带操作(价值 3w + 的嵌入式开发指南)
  • FFmpeg:M3U8的AES加密
  • 《Android 应用开发基础教程》——第三章:布局管理与 UI 组件详解
  • 多模态大语言模型arxiv论文略读(三十一)
  • 机器学习 Day12 集成学习简单介绍
  • [Windows]_[VS2017]_[如何进行远程调试程序]
  • POSIX标准系统调用详解:从概念到实践
  • 破解吞咽困境!进行性核上性麻痹患者的科学饮食方案
  • 62页华为IPD-MM流程:市场调研理论与实践方案精读【附全文阅读】
  • 细说汇率 ⑬ 美元进入“全是坏消息”阶段
  • 中国英国商会政府事务主席陶克瑞:重庆经济成就瞩目,中英合作机遇无限
  • 王忠诚出任四川遂宁代市长,此前为成都市政府秘书长
  • 男子为讨喜钱掰断劳斯莱斯小金人,警方:已介入处置
  • 商务部24日下午将举行发布会,介绍近期商务领域重点工作情况
  • 《蛮好的人生》上海特色鲜明,聚焦荧屏甚少出现的保险业