刘光辉
119 分钟以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<script lang="ts" setup>
import type { CustomPrintConfig, CustomPrintPreviewExpose } from './types';
 
import { computed, onUnmounted, ref, watch } from 'vue';
import { hiprint as hiprintPlugin } from 'vue-plugin-hiprint';
 
import { useGlobSetting } from '@jnpf/hooks';
 
import { Button, Empty, Result, Spin } from 'ant-design-vue';
 
import { useBaseStore } from '#/store';
import { onlineUtils } from '#/utils/jnpf';
import { resolveBrandAssetUrl } from '#/utils/systemBrand';
 
const props = defineProps<{
  config: CustomPrintConfig;
}>();
 
const emit = defineEmits<{
  error: [message: string];
  loaded: [];
  loading: [loading: boolean];
}>();
 
const baseStore = useBaseStore();
const globSetting = useGlobSetting();
const systemLogoUrl = computed(() => resolveBrandAssetUrl(baseStore.sysConfigInfo.logoIcon, globSetting.apiURL));
 
// 预加载所有打印模板
const templateModules = import.meta.glob('/src/print-templates/**/*.html', {
  eager: true,
  import: 'default',
  query: '?raw',
});
 
// 构建模板路径映射
const templateMap = Object.entries(templateModules).reduce(
  (map, [path, content]) => {
    const publicPath = path.replace('/src', '');
    map[publicPath] = content as string;
    map[publicPath.replace('.html', '')] = content as string;
    return map;
  },
  {} as Record<string, string>,
);
 
const htmlContent = ref('');
const iframeRef = ref<HTMLIFrameElement | null>(null);
const loading = ref(false);
const errorMessage = ref<null | string>(null);
const requestId = ref(0);
 
const effectiveType = computed<NonNullable<CustomPrintConfig['type']>>(() => props.config.type || 'html-file');
const isHtmlFileMode = computed(() => effectiveType.value === 'html-file');
 
watch(
  [() => props.config, systemLogoUrl],
  () => {
    reload();
  },
  { deep: true, immediate: true },
);
 
onUnmounted(() => {
  requestId.value++;
});
 
function normalizeTemplatePath(filePath: string) {
  let normalizedPath = filePath;
  const match = filePath.match(/(\/[^/]+_app_[^/]+)(\/print-templates\/)/);
  const appPrefix = match?.[1];
  if (appPrefix) {
    normalizedPath = filePath.replace(appPrefix, '');
  }
 
  if (!normalizedPath.includes('/')) {
    normalizedPath = `/print-templates/${normalizedPath}`;
  } else if (!normalizedPath.startsWith('/')) {
    normalizedPath = `/${normalizedPath}`;
  }
 
  return normalizedPath;
}
 
function findTemplate(filePath: string) {
  const normalizedPath = normalizeTemplatePath(filePath);
  const html = templateMap[normalizedPath] || templateMap[`${normalizedPath}.html`];
 
  if (!html) {
    throw new Error(`模板文件不存在: ${normalizedPath},请确保文件放在 src/print-templates/ 目录下`);
  }
 
  return html;
}
 
function injectSystemLogo(html: string) {
  const logoUrl = systemLogoUrl.value;
  if (!logoUrl) return html.replaceAll('src="/logo.png"', 'style="display:none"');
 
  const escapedUrl = logoUrl
    .replaceAll('\\', '\\\\')
    .replaceAll("'", String.raw`\'`)
    .replaceAll('"', '&quot;');
  return html.replaceAll('src="/logo.png"', `src="${escapedUrl}" onerror="this.style.display=\\'none\\'"`);
}
 
function setLoading(value: boolean) {
  loading.value = value;
  emit('loading', value);
}
 
async function loadHtmlFile(filePath: string, currentRequestId: number) {
  setLoading(true);
  errorMessage.value = null;
 
  try {
    const html = injectSystemLogo(findTemplate(filePath));
    const dataScript = `<script>window.templateData = ${JSON.stringify(props.config.data || {})};</scr${'ipt'}>`;
    let renderedHtml = dataScript + html;
    renderedHtml = await convertImagesToBase64(renderedHtml);
 
    if (currentRequestId !== requestId.value) return;
 
    htmlContent.value = renderedHtml;
    setLoading(false);
    emit('loaded');
  } catch (error: any) {
    if (currentRequestId !== requestId.value) return;
 
    console.error('[CustomPrintPreviewPane] 加载HTML模板失败:', error);
    const message = error.message || '加载模板失败';
    errorMessage.value = message;
    setLoading(false);
    emit('error', message);
  }
}
 
// 将图片转换为 base64(用于 iframe 内联显示)
async function convertImagesToBase64(html: string): Promise<string> {
  const imgRegex = /src=["'](\/[^"']+\.(?:png|jpg|jpeg|gif|svg))["']/gi;
  const matches = [...html.matchAll(imgRegex)];
 
  if (matches.length === 0) return html;
 
  const baseUrl = window.location.origin;
  let result = html;
  for (const match of matches) {
    const fullMatch = match[0];
    const imagePath = match[1];
 
    try {
      const imageUrl = `${baseUrl}${imagePath}`;
      const base64Data = await fetchImageAsBase64(imageUrl);
 
      if (base64Data) {
        result = result.replace(fullMatch, `src="${base64Data}"`);
      }
    } catch (error) {
      console.warn(`[CustomPrintPreviewPane] 无法加载图片: ${imagePath}`, error);
    }
  }
 
  return result;
}
 
async function fetchImageAsBase64(url: string): Promise<null | string> {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
 
    const blob = await response.blob();
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.addEventListener('loadend', () => resolve(reader.result as string));
      reader.addEventListener('error', () => reject(new Error('FileReader error')));
      reader.readAsDataURL(blob);
    });
  } catch (error) {
    console.error(`[CustomPrintPreviewPane] 获取图片失败: ${url}`, error);
    return null;
  }
}
 
function browserPrint() {
  if (!iframeRef.value?.contentWindow) return;
 
  try {
    iframeRef.value.contentWindow.print();
  } catch (error) {
    console.error('[CustomPrintPreviewPane] iframe 打印失败:', error);
  }
}
 
function getPrintableHtml() {
  if (isHtmlFileMode.value) {
    const documentElement = iframeRef.value?.contentDocument?.documentElement;
    return documentElement ? `<!doctype html>${documentElement.outerHTML}` : '';
  }
 
  if (!htmlContent.value) return '';
  if (/<html[\s>]/i.test(htmlContent.value)) return htmlContent.value;
  return `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8" /></head><body>${htmlContent.value}</body></html>`;
}
 
function getPrintLayoutStyles(sourceDocument: Document) {
  const layoutRules: string[] = [];
 
  for (const styleSheet of sourceDocument.styleSheets) {
    try {
      for (const rule of styleSheet.cssRules) {
        if (rule.type !== CSSRule.MEDIA_RULE) continue;
 
        const mediaRule = rule as CSSMediaRule;
        if (!mediaRule.media.mediaText.includes('print')) continue;
 
        for (const printRule of mediaRule.cssRules) {
          if (printRule.type !== CSSRule.STYLE_RULE) continue;
 
          const selector = (printRule as CSSStyleRule).selectorText;
          const isVisibilityRule = selector.includes('.print-pages') || selector.includes('.screen-view');
          const isPageLayoutRule = selector.includes('.page-section') && !/\b(?:tbody|td|th|thead|tr)\b/.test(selector);
          if (isVisibilityRule || isPageLayoutRule) layoutRules.push(printRule.cssText);
        }
      }
    } catch {
      // 跨域样式表无法读取规则时,保留原始 link 标签供 Hiprint 渲染。
    }
  }
 
  return layoutRules.join('');
}
 
function getHiprintPdfContent() {
  const sourceDocument = isHtmlFileMode.value ? iframeRef.value?.contentDocument : new DOMParser().parseFromString(getPrintableHtml(), 'text/html');
  if (!sourceDocument?.body) return '';
 
  const styles = [...sourceDocument.head.querySelectorAll('link[rel~="stylesheet"], style')]
    .map((node) => {
      const clonedNode = node.cloneNode(true) as HTMLElement;
      if (clonedNode instanceof HTMLLinkElement) clonedNode.href = (node as HTMLLinkElement).href;
      return clonedNode.outerHTML;
    })
    .join('');
  const layoutStyles = getPrintLayoutStyles(sourceDocument);
  const content = sourceDocument.body.cloneNode(true) as HTMLBodyElement;
  content.querySelectorAll('.no-print, script').forEach((node) => node.remove());
 
  return `${styles}<style>
    ${layoutStyles}
    .jnpf-hiprint-pdf { box-sizing: border-box; width: 210mm; min-height: 297mm; margin: 0; padding: 0; background: #fff; }
    .jnpf-hiprint-pdf .screen-view { display: none !important; }
    .jnpf-hiprint-pdf .print-pages { display: block !important; }
  </style><div class="jnpf-hiprint-pdf">${content.innerHTML}</div>`;
}
 
function downloadPdfBlob(pdf: Blob, fileName: string) {
  const link = document.createElement('a');
  const url = URL.createObjectURL(pdf);
  link.download = fileName.endsWith('.pdf') ? fileName : `${fileName}.pdf`;
  link.href = url;
  link.click();
  window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
 
async function downloadPdf(fileName: string): Promise<boolean> {
  try {
    const content = getHiprintPdfContent();
    if (!content || !(await onlineUtils.isHiprintClientConnected())) return false;
 
    const template = new hiprintPlugin.PrintTemplate({
      template: {
        panels: [
          {
            height: 297,
            index: 0,
            name: 'PDF',
            paperFooter: 297,
            paperHeader: 0,
            paperType: 'A4',
            printElements: [
              {
                options: {
                  content,
                  height: 297,
                  left: 0,
                  top: 0,
                  width: 210,
                },
                printElementType: { title: 'HTML', type: 'html' },
              },
            ],
            width: 210,
          },
        ],
      },
    });
    const pdf = await template.toPdf({}, fileName, { isDownload: false, type: 'blob' });
    downloadPdfBlob(pdf as Blob, fileName);
    return true;
  } catch (error) {
    console.warn('[CustomPrintPreviewPane] Hiprint PDF 导出失败,将使用浏览器打印:', error);
    return false;
  }
}
 
async function hiprint(options: Omit<Parameters<typeof onlineUtils.hiprint>[0], 'html' | 'template'> = {}) {
  const html = getPrintableHtml();
  if (!html) {
    const error = new Error('打印内容尚未加载完成');
    console.error('[CustomPrintPreviewPane] 打印内容尚未加载完成');
    onlineUtils.toast('打印内容尚未加载完成', 'error');
    options.onError?.(error);
    return;
  }
  return onlineUtils.hiprint({ ...options, html, htmlPrintMode: isHtmlFileMode.value ? 'template' : 'document' });
}
 
function reload() {
  const currentRequestId = requestId.value + 1;
  requestId.value = currentRequestId;
  htmlContent.value = '';
  errorMessage.value = null;
 
  if (isHtmlFileMode.value && props.config.template) {
    loadHtmlFile(props.config.template, currentRequestId);
    return;
  }
 
  htmlContent.value = props.config.template || '';
  setLoading(false);
  emit('loaded');
}
 
defineExpose<CustomPrintPreviewExpose>({ browserPrint, downloadPdf, hiprint, reload });
</script>
 
<template>
  <div class="custom-print-preview-pane">
    <div v-if="loading" class="loading-state">
      <Spin size="large" tip="加载模板中..." />
    </div>
 
    <div v-else-if="errorMessage" class="error-state">
      <Result status="error" title="加载模板失败" :sub-title="errorMessage">
        <template #extra>
          <Button type="primary" @click="reload">重新加载</Button>
        </template>
      </Result>
    </div>
 
    <div v-else-if="isHtmlFileMode && htmlContent" class="iframe-container">
      <iframe ref="iframeRef" class="print-iframe" :srcdoc="htmlContent" frameborder="0"></iframe>
    </div>
 
    <div v-else-if="effectiveType === 'html' && htmlContent" class="html-template-wrapper" v-html="htmlContent"></div>
 
    <div v-else class="empty-state">
      <Empty description="未配置打印模板" />
    </div>
  </div>
</template>
 
<style lang="scss" scoped>
.custom-print-preview-pane {
  width: 100%;
  height: 100%;
 
  .iframe-container {
    width: 100%;
    height: 100%;
    background: white;
  }
 
  .print-iframe {
    width: 100%;
    height: 100%;
    background: white;
    border: none;
  }
 
  :deep(.html-template-wrapper) {
    min-height: 100%;
    background: white;
 
    table {
      border-collapse: collapse;
    }
 
    img {
      max-width: 100%;
    }
  }
 
  .loading-state,
  .error-state {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    background: white;
  }
 
  .empty-state {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 400px;
    background: white;
  }
}
</style>