<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('"', '"');
|
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>
|