实现部分
<div ref="printView">
//需要打印的内容
</div>
<el-button @click="printView" type="primary">打印</el-button>
//引入
import html2canvas from "html2canvas";
import printJS from 'print-js'
//此处省略
//方法函数
printView() {
html2canvas(this.$refs.printView, {
backgroundColor: 'white',
useCORS: true, //允许加载跨域图片并渲染到Canvas 中。
foreignObjectRendering: false, //禁用 foreignObject 渲染(主要用于 SVG 内容)。
windowWidth: document.body.scrollWidth, //截图区域大小为整个文档的宽高。
windowHeight: document.body.scrollHeight,
x: 0, //截图起始坐标为 (0, 0)。
y: 0,
allowTaint: true, //如果设为 true,即使图片跨域也可以绘制,但会失去 toDataURL() 的能力(即不能导出图片)。如果只是截图显示,可以设为 true。如果需要导出图片,则设为 false 并确保图片源允许跨域访问。
taintTest: false, //是否执行污染测试,设为 false 可提升性能,因为跳过检测。
dpi: window.devicePixelRatio * 2, //将分辨率提高到特定的DPI 提高2倍
scale: 4 //放大四倍以提高截图清晰度。
}).then((canvas) => {
const url = canvas.toDataURL()
this.img = url
printJS({
printable: url, //要打印的内容是上一步生成的图片地址。
type: 'image', //指定打印类型为图片。可选值:'html':直接打印 HTML 内容。'json':打印 JSON 数据表。'image':打印图片。'raw-html':原始 HTML 字符串。
documentTitle: "--", //打印文档标题,这里设为 "--"。
base64: 'true', //告诉 printJS 传入的是 Base64 图片数据。 'true':表示传入的是 Base64 数据。'false':表示传入的是 URL。
style: '@page { size: auto; margin: 0mm; } @media print { body { margin: 0mm; } }'//自定义打印样式,设置页面大小为自动 (size: auto) 并移除默认页边距 (margin: 0mm)。
})
});
},
存在问题
使用此方法会导致在打印时输入框的文字内容会向上偏移
题外话:博主之前写了一次,但由于忘了提交代码导致这部分代码丢失,又写了一遍,但却没有上次实现的好,痛定思痛,决定记录下来