Angular 需要浏览器插件吗?
不需要。安装本地客户端 + npm 包即可。
在 Angular 15+ 管理后台中,通过 Injectable 服务封装 web-print-pdf 的 printHtml,实现无浏览器弹窗静默出纸。npm API 与 Vue、React 专题完全一致。
npm install web-print-pdf组件触发打印 → Angular 服务调用 printHtml → npm 经本地 WebSocket 提交 → 客户端渲染 PDF 并出纸。原理见 window.print 替代。
创建可注入的打印服务,在组件中调用:
import { Injectable } from '@angular/core';
import webPrintPdf from 'web-print-pdf';
@Injectable({ providedIn: 'root' })
export class SilentPrintService {
async printHtml(html: string) {
return webPrintPdf.printHtml(
html,
{ paperFormat: 'A4', printBackground: true },
{ paperFormat: 'A4', printerName: 'Default printer' }
);
}
}
@Component({
template: `
<button (click)="onPrint()" [disabled]="loading">
{{ loading ? 'Printing…' : 'Silent print' }}
</button>
`
})
export class ReportPrintComponent {
loading = false;
constructor(private print: SilentPrintService) {}
async onPrint() {
this.loading = true;
try {
await this.print.printHtml(document.getElementById('report')!.innerHTML);
} finally {
this.loading = false;
}
}
}
angular.json 中无需特殊配置;确保打印逻辑仅在浏览器端执行(勿在 SSR 服务端 import)。@ViewChild 获取表格容器 DOM,或维护独立打印模板。getConnectStatus() 预检;失败处理见 错误处理。async 管道或 firstValueFrom 中调用 printHtml 均可。Material 表格打印时容易把 paginator、sort header 或 sidenav 一起打进纸面。
mat-sidenav-container不需要。安装本地客户端 + npm 包即可。
printHtml 只能在浏览器端调用;SSR 页面请在组件 ngOnInit 之后、用户点击时触发。
npm API 相同,仅 Angular 用 Service/DI 组织代码。
移除 fixed/sticky 列容器,或使用不含 Material chrome 的打印专用 HTML 模板。
在 Effect 完成后的组件点击事件中调用 printHtml;避免在 reducer 内直接触发打印。
同一套 web-print-pdf 前端代码可在 Windows、macOS、Linux/信创混合环境运行;请按终端操作系统安装对应客户端。