CKEditor 5如何实现点击按钮唤起浏览器打印预览功能
CKEditor 5 打印预览功能实现方案
CKEditor 5 没有对外暴露独立的打印预览调用API,分页插件自带的打印预览是插件内部实现的逻辑,不需要强行找内置接口,直接通过原生JS结合编辑器实例方法实现即可,完全匹配唤起浏览器打印预览的需求。
之前参考的旧方案是针对CKEditor 4版本编写的,和CKEditor 5的实例获取、API结构不兼容,在Angular 9环境下会出现函数未定义的报错,以下是可直接运行的适配方案,支持两种按钮放置方式:
- 按钮放置在文档顶部、编辑器外部
- 按钮直接加入CKEditor编辑器工具栏
核心实现逻辑
和分页插件自带的打印预览逻辑一致:提取编辑器内的完整HTML内容,打开临时窗口写入内容和打印适配样式,待页面加载完成后自动唤起浏览器原生打印预览,打印/取消打印后自动关闭临时窗口,可正常识别编辑器内插入的分页符,打印时自动分页。
Angular 9 环境实现代码
1. 组件TS层逻辑
import { Component, ViewChild } from '@angular/core'; import { CKEditorComponent } from '@ckeditor/ckeditor5-angular'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; @Component({ selector: 'app-document-view', templateUrl: './document-view.component.html' }) export class DocumentViewComponent { @ViewChild(CKEditorComponent) editorRef!: CKEditorComponent; public editorInstance = ClassicEditor; public editorConfig = { toolbar: ['heading', '|', 'bold', 'italic', 'pageBreak', '|', 'printPreview'] }; // 编辑器就绪回调,用于注册工具栏自定义打印按钮 onEditorReady(editor: any): void { // 注册自定义工具栏按钮 editor.ui.componentFactory.add('printPreview', (locale) => { const printBtn = editor.ui.componentFactory.create('button'); printBtn.set({ label: '打印预览', withText: true, tooltip: '打开打印预览' }); printBtn.on('execute', () => this.openPrintPreview()); return printBtn; }); } // 打印预览触发方法,顶部外部按钮和工具栏按钮共用 openPrintPreview(): void { const editor = this.editorRef.editorInstance; if (!editor) return; const content = editor.getData(); // 打开临时打印窗口 const printWin = window.open('', '_blank', 'width=900,height=750'); if (!printWin) return; // 写入内容和打印样式 printWin.document.write(` <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>文档打印</title> <style> * { box-sizing: border-box; } body { padding: 24px; max-width: 210mm; margin: 0 auto; font-family: "Microsoft Yahei", sans-serif; line-height: 1.6; } img { max-width: 100%; } /* 适配分页符样式 */ .page-break { page-break-after: always; break-after: page; border: none; margin: 2rem 0; } @media print { body { padding: 0; } .page-break { margin: 0; } } </style> </head> <body>${content}</body> <script> window.onload = () => { window.print(); window.onafterprint = () => window.close(); } </script> </html> `); printWin.document.close(); } }
2. 组件模板层写法
<!-- 文档顶部的外部打印按钮 --> <div class="document-toolbar"> <button type="button" (click)="openPrintPreview()">打印预览</button> </div> <!-- CKEditor 编辑器实例 --> <ckeditor [editor]="editorInstance" [config]="editorConfig" [data]="documentContent" (ready)="onEditorReady($event)" ></ckeditor>
该方案不需要依赖任何未公开的CKEditor内部API,不存在版本兼容问题,可根据需求选择保留顶部外部按钮、编辑器工具栏按钮其中任意一种,或者两种同时保留。
内容的提问来源于stack exchange,提问作者dharani kumar
相关产品推荐
相关产品推荐

