打印时格式有变
需要将当前页面转为canvas,然后jsPdf打印
首先新建一个htmlToPdf.js
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
install(Vue) {
Vue.prototype.getPdf = function () {//绑定全局方法
let _this=this
html2Canvas(document.querySelector('#printContent'), {//指定的需要转pdf的接结点位置
allowTaint: true
}).then(function (canvas) { //绘制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()
}
}
}
//用于弹出预览框
_this.$refs.previewandprint.visible=true;
_this.$refs.previewandprint.previewandprintaa(PDF);
})
}
}
}
新建一个PreviewAndPrintModal框
<template>
<a-modal
style="position: absolute;left: 0;top: 0;right: 0;"
:width="1300"
:visible="visible"
@cancel="handleCancel">
<div id="usetosaveiframe"></div>
</a-modal>
</template>
<script>
export default {
name: "PreviewAndPrintModal",
data(){
return {
visible:false,
//存放带来的PDF页面
previewPdf:'',
//存放ifram的外层DOM
contentDom:'',
//存放ifram展示PDF
iframe:''
}
},
updated(){
//显示时 新建ifame标签在线展示pdf 关闭时 移出iframe标签
if(this.visible){
// 新建ifame标签在线展示pdf
this.contentDom = document.querySelector('#usetosaveiframe')
this.iframe = document.createElement('iframe')
this.iframe.height = '1000px'
this.iframe.width = '99%'
this.contentDom.appendChild(this.iframe)
this.iframe.src = this.previewPdf.output('datauristring')
}else{
this.contentDom.removeChild(this.iframe)
}
},
methods:{
previewandprintaa(pdf){
this.previewPdf=pdf
},
close () {
this.$emit("closeit")
this.visible = false;
},
handleCancel () {
this.close()
},
}
}
</script>
<style scoped>
</style>
使用的页面