1、mm转px,生成图片的固定宽高
//获取设备dpi(分辨率)
getDPI() {
var arrDPI = new Array();
if (window.screen.deviceXDPI != undefined) {
arrDPI[0] = window.screen.deviceXDPI;
arrDPI[1] = window.screen.deviceYDPI;
} else {
var tmpNode = document.createElement("DIV");
tmpNode.style.cssText =
"width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
document.body.appendChild(tmpNode);
arrDPI[0] = parseInt(tmpNode.offsetWidth);
arrDPI[1] = parseInt(tmpNode.offsetHeight);
tmpNode.parentNode.removeChild(tmpNode);
}
return arrDPI;
},
//mm单位转化为像素单位
mmConversionPx(value) {
var inch = value / 25.4;
var c_value = inch * this.getDPI()[0];
return c_value;
},
2、初始化dom元素的宽高
//js
this.width = parseInt(this.mmConversionPx(130))
this.height = parseInt(this.mmConversionPx(65))
//html
<div
ref="printPage"
class="printPadding"
:style="{ width: width + 'px', height: height + 'px' }"
>
3、生成图片并打印
//首先需要安装html2canvas 和print-js 插件并引入,配置请参考文档
//https://github.com/crabbly/Print.js
//https://github.com/niklasvh/html2canvas
方法1:生成的图片会模糊
print() {
html2canvas(this.$refs.printPage, {
scale: 0.85,
dpi: 300,
background: "#ffffff", // 一定要添加背景颜色,否则出来的图片,背景全部都是透明的
}).then((canvas) => {
const url = canvas.toDataURL();
this.src = url;
printJS({
printable: url,
type: "image",
style: "@page {margin:0mm 0mm}", //去除页眉页脚
});
});
},
方法二:增加canvas像素
//参考https://blog.csdn.net/weixin_44309374/article/details/106924138
print() {
// 获取想要转换的 DOM 节点
const dom = document.querySelector(".printPadding");
// 获取像素比
scaleBy = 5;
// 创建自定义 canvas 元素
const canvas = document.createElement("canvas");
// 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
canvas.width = this.width * scaleBy;
canvas.height = this.height * scaleBy;
// 获取画笔
const context = canvas.getContext("2d");
// 将所有绘制内容放大像素比倍
// context.scale(scaleBy, scaleBy);
// 将自定义 canvas 作为配置项传入,开始绘制
html2canvas(dom, { canvas, dpi:300,scale: 2.7, background: "#ffffff" }).then(
(imgDom) => {
let url = imgDom.toDataURL();
this.src = url;
// return;
printJS({
maxWidth:this.width,
printable: url,
type: "image",
targetStyle:{
width:this.width+'px',
height:this.height+'px'
},
style: "@page {margin:0mm 0mm}", //去除页眉页脚
});
}
);
},
4、针式打印机打印图片模糊
选择打印html;
//调用打印机
print() {
let style = "@page {margin:0mm 0mm}";
style += `
@media print {
.title {
font-size: 30px !important;
margin-bottom: 5px;
font-weight: bold;
text-align: center;
}
}
`;
printJS({
printable: this.$refs.printPage,
type: "html",
style: style, //去除页眉页脚
});
原理:
1、创建iframe标签,把打印内容放在iframe里面
2、把style的内容放在head里面
问题:最开始设置字体大小无效,后看源码发现 font-size 默认设置了!important ,取消即可
项目git地址:出库单打印
项目截图:
项目功能:对出版社的增删改查和打印出版社单子
感想:解决问题最有效的方式就是看其原理;最开始百度了好久,都无法搜出解决方案,脑袋瓜就一直没想过调试源码;