Nuxt3 页面里直接 import 打印 SDK,一刷新服务端报 document is not defined,或打包把 Node 环境搞炸。
直说吧:
打印是浏览器能力。Nuxt 里必须 client only:插件 ssr: false,或动态 import,或只在 onMounted / 点击里调。
// plugins/print.client.ts
import webPrintPdf from 'web-print-pdf';
export default defineNuxtPlugin(() => {
return {
provide: {
silentPrint: async (html, printerName) => {
if (!(await webPrintPdf.utils.getConnectStatus())) {
throw new Error('本机打印客户端未运行');
}
return webPrintPdf.printHtml(
html,
{
paperFormat: 'A4', printBackground: true },
{
printerName },
{
action: 'print' }
);
},
},
};
});
页面:
<script setup>
const { $silentPrint } = useNuxtApp();
async function onPrint() {
const html = document.querySelector('#print-area')?.innerHTML || '';
await $silentPrint(html, '仓-激光-01');
}
</script>
和 Next.js 那篇同一原则:Server Component / 服务端函数打不了本地打印机。
排障表
| 现象 | 先查 |
|---|---|
| document is not defined | 插件未标 client;或顶层就调了 |
| 水合后按钮无效 | 点击逻辑是否包在客户端 |
| 连不上 | 工位客户端与 LNA |
Nuxt 搜「静默打印」的人多半踩过 SSR。点明边界,再给 web-print-pdf,少绕一天。