打印
开始打算直接用原始的 window.print() 但很曲折,打印出来没有样式还会有各种各样的问题,然后直接放弃
1、首先 npm install vue-print-nb --save
2、然后在main.js 里面引入并且注册(
import Print from 'vue-print-nb'
Vue.use(Print)
3、在你想要打印的那个模块行内添加id=‘名字’
4、在你点击的按钮或者是图标上添加v-print
v-print="printObj" // 'printObj'是下一个步骤里面起的名字
5、在data中添加一个’printObj’
data() {
return {
printObj: {
id: "printer", // 上面绑定的id名字
popTitle: '标题名字', // 需要显示的标题名字
extraCss: 'https://www.google.com,https://www.google.com',
extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>'
},
};
},
这样打印的话就可以了(只要保证层级没问题,图片在打印预览的时候可以显示)
导出pdf
1、npm装两个包
第一个.将页面html转换成图片
npm install --save html2canvas
第二个.将图片生成pdf
npm install jspdf --save
2、在你想导出的那个模块行内添加一个id=‘pinter’
3、在你点击的按钮或者是图标上添加一个点击事件(这个名字是下一个步骤的方法名)
@click="downloadHtmlToPdf()"
4、在文件夹中新建一个文件取名downloadHtmlToPdf
然后在文件里面写入下面的内容注意里面的#printer是你绑定的id(上面第二步骤的id)
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
install(Vue, options) {
Vue.prototype.downloadHtmlToPdf = function () {
var title = this.htmlTitle
html2Canvas(document.querySelector('#printer'), { // 这个id很重要,一旦填写错了或者不填写就会报错
allowTaint: true,
useCORS: true
}).then(function (canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
}
)
}
}
}
5、在main.js里面引入上面写的文件并且注册
import downloadHtmlToPdf from '@/util/downloadHtmlToPdf'
Vue.use(downloadHtmlToPdf)
这样就算页面中有img图片也可以导出