前端实现打印网页内容的解决方案(附完整代码)
目录
技术实现:
打印方法通过js原生封装,
框架采用的是vue和elementplus(单纯想实验一下打印方法的可以不用,直接复制下方代码块即可)
实现逻辑:
1.函数入口printHtml,传入对应的参数,节点,缩放比例(可以使百分比或数字 但不能为负)以及覆盖样式。
2.样式设置: 调用 getStyle 函数以获取打印相关的样式,并传入缩放比例和覆盖样式。
3.容器创建: 调用 getContainer 函数,将需要打印的 HTML 内容放入一个新的 DOM 元素(div)添加到文档: 将样式和内容容器添加到 body 中以便于打印。
4.加载图片: 调用 getLoadPromise 函数确保所有图片加载完成后,才触发打印操作。打印完成后清理: 打印完成后,移除添加的样式和内容容器。
封装方法代码如下:
export default function printHtml( html: any, zoom?: any, overrideStyle?: string ) { const style = getStyle(zoom, overrideStyle); const container = getContainer(html); document.body.appendChild(style); document.body.appendChild(container); getLoadPromise(container).then(() => { window.print(); document.body.removeChild(style); document.body.removeChild(container); }); } function getStyle(zoom?: any, overrideStyle?: string) { const styleContent = ` #print-container { display: none; zoom:${zoom ?? "normal"}; } @media print { body > :not(.print-container) { display: none; } html, body { display: block !important; } body { height:auto; } #print-container { display: block; } }` + overrideStyle; const style = document.createElement("style"); style.innerHTML = styleContent; return style; } function cleanPrint() { const div = document.getElementById("print-container"); if (!!div) { document.querySelector("body")?.removeChild(div); } } function getContainer(html: any) { cleanPrint(); const container = document.createElement("div"); container.setAttribute("id", "print-container"); container.innerHTML = html; return container; } function getLoadPromise(dom: any) { let imgs = dom.querySelectorAll("img"); imgs = [].slice.call(imgs); if (imgs.length === 0) { return Promise.resolve(); } let finishedCount = 0; return new Promise((resolve) => { function check() { finishedCount++; if (finishedCount === imgs.length) { resolve({}); } } imgs.forEach((img: any) => { img.addEventListener("load", check); img.addEventListener("error", check); }); }); }
调用:
具体调用可以参考一下下方的vue代码,我是将打印的内容放入到自己二次封装的弹框中去了
喚起打印推弹框 居民个人信息伊恩加拉格 18100000000 南区 School No.1188, Wuzhong Avenue, Wuzhong District, Suzhou, Jiangsu Province
实现效果如下:
总结
到此这篇关于前端实现打印网页内容解决方案的文章就介绍到这了,更多相关前端打印网页内容内容请搜索科站长以前的文章或继续浏览下面的相关文章希望大家以后多多支持科站长!
栏 目:JavaScript
本文地址:https://www.fushidao.cc/wangluobiancheng/3184.html
您可能感兴趣的文章
- 02-11js中基本事件的总结(onclick、onblur、onchange等)
- 02-11详解如何在Node.js中使用中间件处理请求
- 02-11Vue3中Provide和Inject的用法及工作原理详解
- 02-11Vue+vant实现图片上传添加水印
- 02-11快速解决 keep-alive 缓存组件中定时器干扰问题
- 02-11uniapp 使用 tree.js 解决模型加载不出来的问题及解决方法
- 02-11基于uniapp vue3 的滑动抢单组件实例代码
- 02-10JavaScript 中的 Map使用指南
- 02-10vue3中使用print-js组件实现打印操作步骤
- 02-10Vue 中v-model的完整用法及v-model的实现原理解析


阅读排行
推荐教程
- 04-23JavaScript Array实例方法flat的实现
- 04-23THREE.JS使用TransformControls对模型拖拽的代码实例
- 04-23Vue3使用v-if指令进行条件渲染的实例代码
- 04-23vue3+ts项目搭建的实现示例
- 04-23JavaScript实现下载超大文件的方法详解
- 04-23vue如何使用pdf.js实现在线查看pdf文件功能
- 04-23vue.js调用python脚本并给脚本传数据
- 12-18使用JavaScript遍历输出页面中的所有元素的方法详解
- 04-23JS加密解密之保存到桌面书签
- 12-18Vue实现滚动加载更多效果的示例代码