Angular 后台一点打印就 window.print(),弹框还带侧栏。要静默、指定机,又不想为大改模块扯皮。
直说吧:
和 Vue/React 一样:浏览器里取 HTML,本机客户端出纸。注意在浏览器平台调用,别塞进服务端渲染路径。
import {
Injectable } from '@angular/core';
import webPrintPdf from 'web-print-pdf';
@Injectable({
providedIn: 'root' })
export class SilentPrintService {
async printElement(selector: string, printerName: string) {
if (!(await webPrintPdf.utils.getConnectStatus())) {
throw new Error('本机打印客户端未运行');
}
const el = document.querySelector(selector);
if (!el) throw new Error('打印区域不存在');
return webPrintPdf.printHtml(
el.innerHTML,
{
paperFormat: 'A4', printBackground: true },
{
printerName },
{
action: 'print' }
);
}
}
组件里:
await this.silentPrint.printElement('#print-area', '财务-A4-01');
样式尽量打进打印区(内联或打印专用 CSS),别依赖整站全局主题在客户端里还能拉到。
排障表
| 现象 | 先查 |
|---|---|
| 构建报错找不到包 | 依赖安装;允许 commonjs 等按项目配置 |
| 出纸无样式 | 外链 CSS 未进 HTML |
| SSR 报 document | 调用放在浏览器事件里 |
| 连不上 | 客户端、LNA |
Angular 长尾还在不少政企后台。最小服务一包住,web-print-pdf 就能进柜面。