在需要打印功能的组建中
import print from 'print-js'通用写法:
<div id="printContent"> 打印这些html</div> <button @click="openPrint()">点击打印</button> openPrint(){ printJS({ printable: 'printContent',// // 文档来源:pdf或图像的url,html元素的id或json数据的对象 type: 'json', // 可打印的类型。可用的打印选项包括:pdf,html,图像,json和raw-html。 targetStyles: ['*'] // 库在打印HTML元素时处理任何样式 }) }1.刚开始写打印功能的时候,先百度一下。找了一些单纯的js写法来实现:
手动创建一个iframe,打印这个iframe的内容
openPrint(){ //判断iframe是否存在,不存在则创建iframe var iframe=document.getElementById("printContent"); if(!iframe){ var el = document.getElementById("printcontent"); iframe = document.createElement('IFRAME'); var doc = null; iframe.setAttribute("id", "print-iframe"); iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-999em;top:-500px;'); //left负值不会出现横向滚动条 document.body.appendChild(iframe); doc = iframe.contentWindow.document; //这里可以自定义样式 //doc.write("<LINK rel="stylesheet" type="text/css" href="css/print.css">"); doc.write('<div>' + el.innerHTML + '</div>'); doc.close(); iframe.contentWindow.focus(); } iframe.contentWindow.print(); if (navigator.userAgent.indexOf("MSIE") > 0){ document.body.removeChild(iframe); } }问题:当打印机构复杂的包含图片、文字、表情的html,会有部分样式丢失。
于是开始考虑找打印插件
2.首先以vue为前提找到了vue-print-nb
npm文档:https://www.npmjs.com/package/vue-print-nb
npm install vue-print-nb --save在main.js中引入
import Print from 'vue-print-nb' Vue.use(Print);之后在组件写打印某些内容的时候可以直接写
<div id="printContent"> 打印这些html</div> <button v-print="#printContent">点击打印</button>或者
<div id="printContent"> 打印这些html</div> <button v-print="openPrint">点击打印</button> export default { data() { return { openPrint: { id: "printContent", popTitle: '打印的标题', extraCss: 'https://www.google.com,https://www.google.com', extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>' } }; } }问题:
当打印机构复杂的包含图片、文字、表情和多张背景图片的html,会有部分样式丢失。导致背景图片超出原来位置,按原图大小展示。打印的内容比较多,浏览器出现滚动条时,只能打印当前可视窗口的内容这个插件,书写简洁。适合打印数据结构不复杂的内容。复杂的内容打印时,暂未发现如何解决以上内容
