<script lang="ts" setup>
|
import { computed, onUnmounted, ref, watch } from 'vue';
|
|
import { Button, Empty, Result, Spin } from 'ant-design-vue';
|
|
import type { CustomPrintConfig, CustomPrintPreviewExpose } from './types';
|
|
const props = defineProps<{
|
config: CustomPrintConfig;
|
}>();
|
|
const emit = defineEmits<{
|
error: [message: string];
|
loaded: [];
|
loading: [loading: boolean];
|
}>();
|
|
// 预加载所有打印模板
|
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,
|
() => {
|
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 setLoading(value: boolean) {
|
loading.value = value;
|
emit('loading', value);
|
}
|
|
async function loadHtmlFile(filePath: string, currentRequestId: number) {
|
setLoading(true);
|
errorMessage.value = null;
|
|
try {
|
const html = findTemplate(filePath);
|
const dataScript = `<script>window.templateData = ${JSON.stringify(props.config.data || {})};<\/script>`;
|
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 print() {
|
if (!iframeRef.value?.contentWindow) return;
|
|
try {
|
iframeRef.value.contentWindow.print();
|
} catch (error) {
|
console.error('[CustomPrintPreviewPane] iframe 打印失败:', error);
|
}
|
}
|
|
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>({ print, 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>
|