41. 模板打印
模板打印(套打)把「版式」和「数据」彻底分离:版式以 JSON 存进 sys_print 表,业务页按模板名取回 JSON,用 @worm-vue3-print 渲染成 HTML 再打印。后端只负责模板 CRUD,真正的渲染与出纸全在浏览器端。
原理与流程
┌──── 设计期(平台管理 → 打印模板) ─────────────────────────────────┐
│ editPrint.vue │
│ └─ wormPrint.vue │
│ ├─ PrintDesigner (@worm-vue3-print/canvas)拖拽设计 │
│ ├─ PrintHtmlPreview 预览:模板 JSON + 数据 → iframe HTML │
│ └─ emit('save', { template: json字符串 }) │
└───────────────────────────┬────────────────────────────────────────┘
│ apiSysPrintAddPost / apiSysPrintUpdatePost
┌───────────────────────────▼────────────────────────────────────────┐
│ SysPrintService (Admin.NET.Core/Service/Print) │
│ Page / GetPrint(name) / AddPrint / UpdatePrint / CopyPrint / Delete │
└───────────────────────────┬────────────────────────────────────────┘
│ 表名 sys_print(EntityTenant,多租户隔离)
┌───────────────────────────▼────────────────────────────────────────┐
│ 运行期(业务页面) │
│ const tpl = await getAPI(SysPrintApi).apiSysPrintGetPrintGet(name) │
│ JSON.parse(tpl.template) │
│ PrintHtmlPreview :template-json + :print-data → iframe → print() │
└─────────────────────────────────────────────────────────────────────┘一、后端:SysPrint 实体
Admin.NET.Core/Entity/SysPrint.cs:
[SugarTable(null, "系统打印模板表")]
[SysTable]
[SugarIndex("i_{table}_n", nameof(Name), OrderByType.Asc)]
public partial class SysPrint : EntityTenant
{
[SugarColumn(ColumnDescription = "名称", Length = 64)]
[Required, MaxLength(64)]
public virtual string Name { get; set; } // 模板名,业务侧靠它取模板(唯一)
[SugarColumn(ColumnDescription = "打印模板", ColumnDataType = StaticConfig.CodeFirst_BigString)]
[Required]
public virtual string Template { get; set; } // 设计器产出的 JSON 字符串
[SugarColumn(ColumnDescription = "打印类型", DefaultValue = "1")]
public virtual PrintTypeEnum PrintType { get; set; } = PrintTypeEnum.Browser;
[SugarColumn(ColumnDescription = "客户端服务地址", Length = 128)]
public virtual string? ClientServiceAddress { get; set; } // PrintType=Client 时的客户端地址
[SugarColumn(ColumnDescription = "打印参数", ColumnDataType = StaticConfig.CodeFirst_BigString)]
public virtual string? PrintParam { get; set; } // 纸张/份数等自定义参数(业务自行约定)
public int OrderNo { get; set; } = 100;
public StatusEnum Status { get; set; } = StatusEnum.Enable;
public string? Remark { get; set; }
[SugarColumn(ColumnDescription = "打印预览测试数据", ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string? PrintDataDemo { get; set; } // 设计器预览用的样例数据
}打印类型枚举 Admin.NET.Core/Enum/PrintTypeEnum.cs:
public enum PrintTypeEnum
{
Browser = 1, // 浏览器打印(默认,直接调 iframe 的 window.print)
Client = 2, // 客户端打印(配合 ClientServiceAddress 走本地打印服务)
}二、后端:SysPrintService
Admin.NET.Core/Service/Print/SysPrintService.cs(Swagger 分组 Order = 305,Description = 打印模板):
[ApiDescriptionSettings(Order = 305, Description = "打印模板")]
public class SysPrintService : IDynamicApiController, ITransient
{
private readonly SqlSugarRepository<SysPrint> _sysPrintRep;
public SysPrintService(SqlSugarRepository<SysPrint> sysPrintRep) => _sysPrintRep = sysPrintRep;
/// 分页,按 OrderNo、Name 排序
public async Task<SqlSugarPagedList<SysPrint>> Page(PagePrintInput input)
{
return await _sysPrintRep.AsQueryable()
.WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name))
.OrderBy(u => new { u.OrderNo, u.Name })
.ToPagedListAsync(input.Page, input.PageSize);
}
/// 业务侧唯一需要关心的接口:按名称取模板
public async Task<SysPrint> GetPrint(string name)
=> await _sysPrintRep.GetFirstAsync(u => u.Name == name);
[ApiDescriptionSettings(Name = "Add"), HttpPost]
public async Task AddPrint(AddPrintInput input)
{
var isExist = await _sysPrintRep.IsAnyAsync(u => u.Name == input.Name);
if (isExist) throw Oops.Oh(ErrorCodeEnum.D1800); // 名称重复
await _sysPrintRep.InsertAsync(input.Adapt<SysPrint>());
}
[ApiDescriptionSettings(Name = "Update"), HttpPost]
public async Task UpdatePrint(UpdatePrintInput input)
{
var isExist = await _sysPrintRep.IsAnyAsync(u => u.Name == input.Name && u.Id != input.Id);
if (isExist) throw Oops.Oh(ErrorCodeEnum.D1800);
await _sysPrintRep.AsUpdateable(input.Adapt<SysPrint>()).IgnoreColumns(true).ExecuteCommandAsync();
}
[ApiDescriptionSettings(Name = "Copy"), HttpPost]
public async Task CopyPrint(DeletePrintInput input)
{
var print = await _sysPrintRep.AsQueryable().Where(u => u.Id == input.Id).FirstAsync();
if (print == null) throw Oops.Bah("模板不存在");
print.Name = print.Name + "_Copy_" + DateTime.Now.ToString("ddHHmmss");
print.Id = 0;
await AddPrint(print.Adapt<AddPrintInput>());
}
[ApiDescriptionSettings(Name = "Delete"), HttpPost]
public async Task DeletePrint(DeletePrintInput input)
=> await _sysPrintRep.DeleteByIdAsync(input.Id);
}对应的接口清单(前端 api 自动生成在 Web/src/api-services/system/apis/sys-print-api.ts):
| 前端方法 | 说明 |
|---|---|
apiSysPrintPagePost | 分页查询 |
apiSysPrintGetPrintGet(name) | 按名称取模板(渲染时用它) |
apiSysPrintAddPost / apiSysPrintUpdatePost | 新增 / 更新 |
apiSysPrintCopyPost | 复制(自动改名,适合基于现有模板改版) |
apiSysPrintDeletePost | 删除 |
三、前端:设计器
依赖(Web/package.json):
"@worm-vue3-print/canvas": "^1.3.5",
"@worm-vue3-print/core": "^1.3.5"样式在入口文件全局引入:
// Web/src/main.ts
// 打印模板
import '@worm-vue3-print/canvas/style.css';设计器组件 Web/src/views/system/print/component/wormPrint.vue 的核心结构:
<template>
<el-dialog v-model="visible" fullscreen draggable destroy-on-close>
<div class="worm-print">
<!-- ① 设计器画布 -->
<PrintDesigner
ref="designerRef"
:initial-template="templateData"
:fields="fields"
:is-edit="true"
:show-help="true"
@preview="onPreview"
@save="onSave"
/>
<!-- ② 预览面板:模板 JSON + 数据 → iframe -->
<Teleport to="body">
<div v-if="previewVisible" class="preview-mask">
<div class="preview-panel">
<div class="preview-head">
<span class="preview-title">打印预览</span>
<span class="preview-subtitle" v-if="previewPages > 0">{{ previewPages }} 页</span>
<button class="preview-btn" @click="printPreview">打印</button>
<button class="preview-btn ghost" @click="previewVisible = false">关闭</button>
</div>
<PrintHtmlPreview
ref="htmlPreviewRef"
class="preview-body"
:template-json="previewJson"
:print-data="printData"
:base-url="baseUrl"
@rendered="(n: number) => (previewPages = n)"
/>
</div>
</div>
</Teleport>
</div>
</el-dialog>
</template>
<script setup lang="ts">
import { ref, computed, watch, type PropType } from 'vue';
import { PrintDesigner, PrintHtmlPreview, createDefaultTemplate } from '@worm-vue3-print/canvas';
import type { PrintBusinessField, TemplateData } from '@worm-vue3-print/core/designer';
const props = defineProps({
data: { type: Object as () => any, default: () => ({}) }, // 打印数据
template: { type: [String, Object] as PropType<string | Record<string, any>>, default: '' },
title: { type: String, default: '打印模板设计' },
fields: { type: Array as () => PrintBusinessField[], default: () => [] }, // 素材台字段目录
});
// 已有模板(编辑场景)用它初始化;不传则空白默认模板
const normalizeTemplate = (t: string | Record<string, any>): TemplateData => {
if (!t) return createDefaultTemplate();
const obj = typeof t === 'string' ? JSON.parse(t) : t;
return obj as TemplateData;
};
const templateData = ref<TemplateData>(normalizeTemplate(props.template));
// 数据原样透传给模板,模板用 {name} 占位符取
const transformData = (raw: Record<string, any>) => {
const result: Record<string, any> = {};
for (const [key, value] of Object.entries(raw ?? {})) {
if (Array.isArray(value)) result[key] = value.map((row) => (row && typeof row === 'object' ? { ...row } : row));
else result[key] = value;
}
return result;
};
const printData = computed(() => transformData(props.data));
const baseUrl = import.meta.env.VITE_API_URL || '';
const previewJson = ref<Record<string, any> | null>(null);
const previewPages = ref(0);
const onPreview = () => {
const json = designerRef.value?.getTemplateJson?.();
if (!json) return;
previewJson.value = json as unknown as Record<string, any>;
previewVisible.value = true;
};
const emit = defineEmits<{ save: [payload: { template: string }] }>();
const onSave = (json: string) => emit('save', { template: json });
defineExpose({ open, close, getTemplateJson: () => designerRef.value?.getTemplateJson?.(), printData });
</script>保存链路在 editPrint.vue:设计器 save → 缓存 JSON → 打开元信息弹窗 → 提交入库。
// Web/src/views/system/print/component/editPrint.vue
const wormTemplateJson = ref<string>('');
const onWormSave = (payload?: { template?: string }) => {
if (payload?.template) wormTemplateJson.value = payload.template;
submit();
};
const templateSubmit = async () => {
state.ruleForm.template = wormTemplateJson.value;
if (state.ruleForm.id != undefined && state.ruleForm.id > 0) {
await getAPI(SysPrintApi).apiSysPrintUpdatePost(state.ruleForm);
} else {
await getAPI(SysPrintApi).apiSysPrintAddPost(state.ruleForm);
}
cancel();
templateCancel();
emits('handleQuery');
};
// 打开弹窗时把库里的模板字符串塞进设计器,并兜底同步进保存缓存
const openDialog = (row: any) => {
state.ruleForm = JSON.parse(JSON.stringify(row));
editTemplate.value = (state.ruleForm.template as string) ?? '';
wormTemplateJson.value = editTemplate.value; // 避免「没点设计器保存直接确定」把模板清空
wormPrintRef.value?.open({ template: editTemplate.value });
ruleFormRef.value?.resetFields();
};四、业务页面消费模板(完整示例)
<template>
<el-button icon="ele-Printer" @click="handlePrint">打印入库单</el-button>
<el-dialog v-model="previewVisible" fullscreen>
<PrintHtmlPreview
ref="htmlPreviewRef"
:template-json="templateJson"
:print-data="printData"
:base-url="baseUrl"
@rendered="(n: number) => (pages = n)"
/>
<template #footer>
<el-button type="primary" @click="doPrint">立即打印</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { PrintHtmlPreview } from '@worm-vue3-print/canvas';
import { getAPI } from '/@/utils/axios-utils';
import { SysPrintApi } from '/@/api-services/system/api';
const TEMPLATE_NAME = '入库单'; // 与 sys_print.Name 完全一致
const previewVisible = ref(false);
const templateJson = ref<Record<string, any> | null>(null);
const pages = ref(0);
const baseUrl = import.meta.env.VITE_API_URL || '';
const htmlPreviewRef = ref<any>(null);
// 打印数据:key 必须与模板里的占位符一致
const printData = reactive({
billNo: 'RK20240101001',
supplier: '某某供应商',
createTime: '2024-01-01 10:00:00',
totalAmount: 1234.56,
// 明细行:模板里用 list 类型字段绑定
items: [
{ name: '螺丝', spec: 'M6', qty: 100, price: 0.5 },
{ name: '螺母', spec: 'M6', qty: 100, price: 0.3 },
],
});
const handlePrint = async () => {
const res = await getAPI(SysPrintApi).apiSysPrintGetPrintGet(TEMPLATE_NAME);
const tpl = res.data.result;
if (!tpl?.template) {
ElMessage.error('打印模板错误');
return;
}
// 库里存的是字符串,必须先 parse
templateJson.value = JSON.parse(tpl.template);
previewVisible.value = true;
};
const doPrint = () => {
// iframe 是独立文档,打印前注入边框修正样式,否则 Chrome 会丢 border-collapse 的边框
const root = htmlPreviewRef.value?.$el ?? htmlPreviewRef.value;
const iframe: HTMLIFrameElement | undefined = root?.querySelector?.('iframe');
if (iframe?.contentDocument?.head && !iframe.contentDocument.getElementById('worm-print-border-fix')) {
const style = iframe.contentDocument.createElement('style');
style.id = 'worm-print-border-fix';
style.textContent = `@media print {
.print-table { border-collapse: separate !important; border-spacing: 0 !important; }
.print-table td:not(:first-child), .print-table th:not(:first-child) { border-left: none !important; }
.print-table tr:not(:first-child) > * { border-top: none !important; }
}`;
iframe.contentDocument.head.appendChild(style);
}
htmlPreviewRef.value?.print();
};
</script>五、代码生成器与打印的联动
代码生成主记录上带两个打印字段:
// Admin.NET.Core/Entity/SysCodeGen.cs
[SugarColumn(ColumnDescription = "支持打印类型")]
public virtual CodeGenPrintTypeEnum PrintType { get; set; }
[SugarColumn(ColumnDescription = "打印模版名称", Length = 32)]
public virtual string? PrintName { get; set; }// Admin.NET.Core/Enum/CodeGenPrintTypeEnum.cs
Off = 1, // 不需要
Custom = 2 // 绑定打印模版(填 PrintName 指定 sys_print.Name)它们会传给模板引擎:
// CodeGenTableStrategyBase.RenderList
input.PrintType = codeGen.PrintType.ToString();
input.PrintName = codeGen.PrintName;⚠️ 当前 /wwwroot/template/web_views_index.vue.vm 里没有引用 PrintType/PrintName(检索无匹配),也就是说生成出来的页面不会自动带打印按钮;需要打印时按上一节的方式自己在生成的 index.vue 里接 SysPrintApi。
六、操作步骤清单
- 打开【平台管理】→【打印模板】→ 新增,弹窗直接进全屏设计器。
- 在左侧素材台拖元素,用
{字段名}占位符绑定数据;fields数组(PrintBusinessField[])由父组件传入,字段类型list表示表格数据源。 - 点设计器「预览」,把样例数据(可先存进
PrintDataDemo)灌进去确认版式与页数。 - 点「保存」→ 填模板名称、排序、状态、打印类型、客户端服务地址(客户端打印时填)、备注 → 确定。
- 后端接口确认:
apiSysPrintGetPrintGet(模板名)能返回template字符串。 - 业务页面引入
PrintHtmlPreview,按模板名取 JSON →JSON.parse→ 传print-data→print()。 - 需要改版时用列表上的「复制」按钮(自动追加
_Copy_ddHHmmss),改完再把业务侧的模板名切换过去。
⚠️ 注意事项与常见坑
- 模板名必须唯一:
AddPrint/UpdatePrint都会查重,重复抛ErrorCodeEnum.D1800。业务侧靠名字取模板,改名等于让所有引用失效。 - 库里取出的是字符串:
Template字段是StaticConfig.CodeFirst_BigString,不JSON.parse直接传给PrintHtmlPreview会渲染失败。 - 占位符大小写敏感:
transformData是原样透传,不做任何字段名转换,模板里写{billNo}数据就必须叫billNo。 - 数组字段要类型一致:
transformData只会对数组里的对象做浅拷贝,基本类型原样保留;混用会导致明细行渲染异常。 - 多租户隔离:
SysPrint继承EntityTenant,SqlSugarRepository自动加租户过滤器,A 租户看不到 B 租户的模板。跨租户取模板需要CopyNew().ClearFilter<ITenantIdFilter>()。 - Chrome 打印丢边框:
iframe是独立文档,外层样式无效,必须像示例那样注入@media print修正样式,否则border-collapse: collapse的表格边框会消失。 baseUrl要传:PrintHtmlPreview的base-url用import.meta.env.VITE_API_URL,模板里引用图片/字体时靠它拼绝对地址,不传会出现图片裂图。- 客户端打印要自己接:
PrintTypeEnum.Client只存了ClientServiceAddress,仓库未提供客户端打印服务的实现,需要按自己的打印机中间件补齐。 - 大数据量分页:
@rendered会回传总页数,建议在打印前提示用户页数,避免误打几百页。
小结
模板打印的后端极轻——SysPrintService 只有 6 个方法,本质是「按名存取 JSON」。真正的价值在前端的 PrintDesigner + PrintHtmlPreview 组合:设计期拖拽出 JSON,运行期用业务数据填充渲染。掌握「模板名唯一 + 取出后 parse + 数据 key 对齐占位符」这三点,就能稳定落地各类单据套打。