<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue3 使用 vue-plugin-hiprint 实现无预览打印</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-plugin-hiprint@latest/dist/vue-plugin-hiprint.js"></script>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
}
button {
padding: 10px 15px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 10px 0;
}
button:hover {
background-color: #369f6b;
}
.print-content {
border: 1px dashed #ccc;
padding: 20px;
margin: 20px 0;
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<h1>Vue3 使用 vue-plugin-hiprint 实现无预览打印</h1>
<p>本示例演示如何使用 vue-plugin-hiprint 插件在 Vue3 中实现无预览直接打印功能。</p>
<div class="print-content">
<h2>打印内容区域</h2>
<p>这是一个示例打印内容,您可以自定义任何需要打印的内容。</p>
</p>
<p>当前时间:{{ currentTime }}</p>
</div>
<button @click="directPrint">直接打印</button>
<button @click="printWithOptions">带选项打印</button>
</div>
</div>
<script>
const { createApp, ref, onMounted } = Vue;
createApp({
setup() {
const currentTime = ref(new Date().toLocaleString());
// 初始化 hiprint
let hiprintInstance = null;
onMounted(() => {
// 创建 hiprint 实例
hiprintInstance = new hiprint.PrintTemplate({
template: {},
settingContainer: '#app', // 通常用于预览,这里我们不需要
});
// 更新当前时间每秒
setInterval(() => {
currentTime.value = new Date().toLocaleString();
}, 1000);
});
// 直接打印
const directPrint = () => {
if (!hiprintInstance) return;
// 获取要打印的 HTML 内容
const printContent = document.querySelector('.print-content').innerHTML;
// 直接打印
hiprintInstance.print(printContent, {
title: '我的打印文档',
styleHandler: () => {
// 可以在这里添加自定义样式
return `
body { font-family: Arial; }
h2 { color: #333; }
p { margin: 5px 0; }
`;
}
});
console.log('打印任务已发送');
};
// 带选项打印
const printWithOptions = () => {
if (!hiprintInstance) return;
const printContent = document.querySelector('.print-content').innerHTML;
// 打印选项
const options = {
title: '自定义打印文档',
copies: 1, // 打印份数
printer: '', // 打印机名称,空表示默认打印机
pageSize: 'A4', // 纸张大小
layout: 'portrait', // 方向: portrait(纵向), landscape(横向)
margin: { // 边距
top: '10mm',
left: '10mm',
right: '10mm',
bottom: '10mm'
},
styleHandler: () => {
return `
body { font-size: 14px; }
h2 { color: #42b983; border-bottom: 1px solid #eee; }
a { color: #42b983; text-decoration: none; }
`;
}
};
hiprintInstance.print(printContent, options);
};
return {
currentTime,
directPrint,
printWithOptions
};
}
}).mount('#app');
</script>
</body>
</html>