fix(打印): 浏览器打印时打印时间为空的兜底处理

This commit is contained in:
liufumingren 2026-09-20 17:08:17 +08:00
parent bf9bba5059
commit 9a0ac370ec

View File

@ -140,7 +140,7 @@
</template>
<script setup lang="ts">
import { computed, h, reactive, ref, watch } from 'vue'
import { computed, h, nextTick, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import JsBarcode from 'jsbarcode'
import QRCode from 'qrcode'
@ -302,6 +302,28 @@ function refreshPages() {
})
}
/** 当前时间 → YYYY-MM-DD HH:mm:ss */
function nowDateTimeStr(): string {
const d = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
/** 兜底补齐打印时间:外部数据未提供 print_time 时填充当前时间,避免打印出空白 */
function ensurePrintTime(form?: Record<string, any>) {
const target = form ?? printForm
const val = target?.print_time
if (val === undefined || val === null || String(val).trim() === '') {
target.print_time = nowDateTimeStr()
}
}
/** 打印(打印台/浏览器)时把打印时间刷新为实际打印时刻并重新分页 */
function markPrintTime() {
printForm.print_time = nowDateTimeStr()
refreshPages()
}
// 切换打印模板时重新分页
watch(
() => printSettings.template,
@ -453,6 +475,9 @@ function getPreviewValue(item: any, data?: any): string {
}
}
// 打印时间:数据里取不到时兜底为当前时间,避免打印出空白
if (item.field_code === 'print_time') return nowDateTimeStr()
// 有 field_code 但无数据时显示空,不回退到占位文字
if (item.field_code) return ''
// 无 field_code 的自定义元素(如固定文字、图片)显示 content
@ -523,6 +548,7 @@ async function loadPrintFormData(index: number) {
const formData = await props.fetchPrintData(mainRow, index)
Object.keys(printForm).forEach(key => delete printForm[key])
Object.assign(printForm, formData || {})
ensurePrintTime(printForm)
refreshPages()
} catch (e) {
console.error('加载打印数据失败', e)
@ -615,6 +641,7 @@ async function loadPrintFormData(index: number) {
Object.keys(printForm).forEach(key => delete printForm[key])
Object.assign(printForm, formData)
ensurePrintTime(printForm)
refreshPages()
}
@ -738,6 +765,8 @@ async function doPrint() {
}
try {
// 打印时间取实际打印时刻
markPrintTime()
const selectedTemplateObj = templateOptions.value.find((item: any) => item.id === printSettings.template) || null
// 逐页发送:当前单据按模板分页,每页一个打印任务(第 2+ 页重复单据头)
const pages = currentPages.value.length > 0 ? currentPages.value : [
@ -790,7 +819,11 @@ async function doPrint() {
}
}
function browserPrint() {
async function browserPrint() {
// 打印时间取实际打印时刻,并等预览 DOM 重新渲染后再拷贝到打印窗口
markPrintTime()
await nextTick()
const previewEls = document.querySelectorAll('.preview-page') as NodeListOf<HTMLElement>
if (!previewEls.length) {
ElMessage.warning('暂无预览内容可打印')