vue 使用print.js 打印文本,HTML元素,图片,PDF
·
vue 使用print.js 打印文本,HTML元素,图片,PDF
- 安装
npm install print-js --save
- 示例
<template>
<div class="print-example">
<h2>Print.js 打印示例</h2>
<!-- 打印区域 -->
<div id="printableArea" class="printable-area">
<h3>这是要打印的内容</h3>
<p>这是一段示例文本,将会被打印出来。</p>
<img src="https://picsum.photos/400/200" alt="示例图片" class="print-image">
<table border="1" cellpadding="8" class="print-table">
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
<tr>
<td>张三</td>
<td>25</td>
</tr>
<tr>
<td>李四</td>
<td>30</td>
</tr>
</table>
</div>
<!-- 打印按钮组 -->
<div class="print-buttons">
<button @click="printText">打印文本</button>
<button @click="printHtml">打印HTML元素</button>
<button @click="printImage">打印图片</button>
<button @click="printPdf">打印PDF</button>
</div>
</div>
</template>
<script>
import print from 'print-js'
import 'print-js/dist/print.css'
export default {
methods: {
// 打印文本
printText() {
print({
printable: '这是一段要打印的文本内容。可以包含多行\n换行文本。',
type: 'raw-html',
header: '文本打印示例',
style: 'p { color: #333; font-size: 14px; }'
})
},
// 打印HTML元素
printHtml() {
print({
printable: 'printableArea', // 元素ID
type: 'html',
header: 'HTML内容打印',
headerStyle: 'font-size: 18px; color: #666;',
maxWidth: 800,
// 自定义打印样式
style: `
.printable-area { padding: 20px; }
.print-table { width: 100%; border-collapse: collapse; margin-top: 10px; }
.print-image { margin: 10px 0; max-width: 100%; }
`
})
},
// 打印图片
printImage() {
print({
printable: 'https://picsum.photos/800/600', // 图片URL
type: 'image',
header: '图片打印示例',
imageStyle: 'max-width: 100%; height: auto;'
})
},
// 打印PDF
printPdf() {
// 注意:打印PDF需要PDF文件的URL
// 这里使用示例PDF,实际项目中替换为你的PDF地址
print({
printable: 'https://sample-videos.com/pdf/Sample-PDF-100kb.pdf',
type: 'pdf',
showModal: true, // 显示加载中模态框
modalMessage: '正在准备PDF文件,请稍候...'
})
}
}
}
</script>
<style scoped>
.print-example {
max-width: 800px;
margin: 20px auto;
padding: 20px;
}
.printable-area {
border: 1px solid #ddd;
padding: 20px;
margin-bottom: 20px;
}
.print-buttons {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
button {
padding: 8px 16px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #359e75;
}
.print-image {
max-width: 100%;
height: auto;
}
.print-table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
</style>
更多推荐
所有评论(0)