遇到一个问题就要用标签打印机打印商品信息,但是写了CSS和打印的CSS相互影响,以下是解决这个问题的方法。
vue-print-nb使用
npm install vue-print-nb --save
或者
yarn add vue-print-nb
局部引用
import Print from 'vue-print-nb';
当然你可以全局引用配置更方便main.js中
import Print from 'vue-print-nb';
Vue.use(Print)
使用
假如你要在100mm*40mm纸上打印这个标签,但是想要沾满整个纸张且不在一张纸上,那么你就要写两套CSS,一套CSS是用来给用户展示你的打印模板(可能需要大点的CSS)你可以<style scoped></style>写一套,另外你打印的时候再写一套只在打印时候生效的CSS,你可以<style scoped></style>其中最要的是要加上@media print
重要的是:如果你两套代码互相影响最好给打印显示的CSS加上!important关键字
<template>
<div>
<el-button type="primary" v-print="'#loctionPrints'">打印</el-button>
<div id="loctionPrints" class="locationimgBox">
<img :src="imageUrl" alt="Image" />
<div>P1001-03-01</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: ''
}
},
created() {
this.imageUrl =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQAQAAAACmas8AAAABGElEQVR42q3TMXbDIAwGYLHgKzgLuRpexBXwgpzFvgJenKuRxb4CLBDaJi1yx1bT9x7voR8BUL4L/s4MUuElayBG2q/lkU3m1KjHx4byRLOWZf5FROHlmXTM5h6+9v0hSKz1yvBmTbdd4/jK+2a20NvaWROjolSOqBxj8V0KsheB8+a7HawyhdGDkkMwN8Z8XaNzZp2oZdmQNrGsS2mZUak6PTETYy/SfRvn2qJl54dJOYXUsixH8iAinOgpatftjFlqiWBSKoyXbFVPkThNAI09fcRpeX9sXTA7p5LKDjsMpWUpGRRqR4z1srQdJhSctJN36JAY64OxJoI708GYPufbsq6CCMBJx+0IlAInSIq2nqi0/M8v8gTrLukc3Yy2ZwAAAABJRU5ErkJggg==';
},
methods: {
}
}
</script>
<style scoped lang="scss">
/* 展示模式样式 */
.locationimgBox {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
box-sizing: border-box;
padding: 10px; /* 增加一些空间,让内容更大 */
}
.locationimgBox img {
width: 100px; /* 设置图像宽度 */
height: 100px; /* 设置图像高度,保持比例 */
object-fit: contain;
}
.locationimgBox div {
font-size: 24px; /* 增加字体大小 */
margin-left: 20px;
}
</style>
<style scoped>
@media print {
/* 设置纸张大小为100mm x 40mm */
@page {
size: 100mm 40mm;
margin: 0;
}
body {
font-family: 'Arial', sans-serif;
font-size: 12px;
color: #333;
margin: 0;
padding: 0;
}
/* 打印模式样式 */
.locationimgBox {
display: flex;
justify-content: center!important;
align-items: center;
width: 100%;
height: 100%;
padding: 2mm; /* 适应小票纸大小,减少内边距 */
}
.locationimgBox img {
width: 20mm !important; /* 设置图像宽度 */
height: 20mm !important; /* 设置图像高度 */
object-fit: contain;
}
.locationimgBox div {
font-size: 16px !important; /* 打印时适当减小字体 */
}
/* 强制去掉浏览器可能存在的任何内外边距 */
body, html {
margin: 0;
padding: 0;
}
/* 强制清除任何浏览器的默认样式,确保打印内容从页面顶部开始 */
body {
margin-top: 0;
}
}
</style>
这是给用户显示的页面
这是打印模板看到的页面
这是另一个标签的打印版本