sop-print.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. import { ElMessage } from 'element-plus'
  2. export const SOP_A4_WIDTH_MM = 210
  3. /** A4 竖版页高 (mm) */
  4. export const SOP_A4_HEIGHT_MM = 297
  5. /** 编辑区在 A4 基础上额外增加的高度 (px) */
  6. export const SOP_EDITOR_EXTRA_HEIGHT_PX = 200
  7. /** 从 SOP HTML 解析页数(class 含 sop-a4-pages-N) */
  8. export function resolveSopPageCount(html: string): number {
  9. const m = html?.match(/sop-a4-pages-(\d+)/)
  10. if (!m) return 1
  11. const n = Number.parseInt(m[1], 10)
  12. return Number.isFinite(n) && n > 0 ? n : 1
  13. }
  14. /** TinyMCE 正文区高度 (px, 96dpi)。init.height 不含工具栏 */
  15. export function getSopA4ContentHeightPx(pages = 1): number {
  16. const p = Math.max(1, pages)
  17. return Math.ceil((SOP_A4_HEIGHT_MM * p * 96) / 25.4)
  18. }
  19. /** TinyMCE 编辑区高度:A4×页数 + 额外空间 */
  20. export function getSopA4EditorHeightPx(pages = 1): number {
  21. return getSopA4ContentHeightPx(pages) + SOP_EDITOR_EXTRA_HEIGHT_PX
  22. }
  23. const SOP_SHARED_CONTENT_STYLE = `
  24. table {
  25. border-collapse: collapse;
  26. width: 100%;
  27. max-width: 100%;
  28. margin-bottom: 16px;
  29. }
  30. table td,
  31. table th {
  32. border: 1px solid #e2e8f0;
  33. padding: 8px;
  34. word-wrap: break-word;
  35. }
  36. table th {
  37. background-color: #f8fafc;
  38. font-weight: 600;
  39. }
  40. .sop-record.sop-a4 {
  41. box-sizing: border-box;
  42. max-width: 210mm;
  43. width: 100%;
  44. margin: 0 auto;
  45. padding: 16mm 15mm 20mm;
  46. background: #fff;
  47. font-size: 10.5pt;
  48. display: flex;
  49. flex-direction: column;
  50. }
  51. .sop-record.sop-a4 table {
  52. margin-bottom: 0;
  53. }
  54. /* 嵌套比例表:去掉 TinyMCE 无边框表虚线辅助框,仅保留标签/选项分隔线 */
  55. .sop-nested-table,
  56. .sop-nested-table.mce-item-table,
  57. .sop-nested-table.mce-item-table:not([border]),
  58. .sop-nested-table.mce-item-table[border='0'],
  59. .sop-nested-table.mce-item-table[border='1'] {
  60. border: none !important;
  61. margin: 0 !important;
  62. }
  63. .sop-nested-table td,
  64. .sop-nested-table th,
  65. .sop-nested-table.mce-item-table:not([border]) td,
  66. .sop-nested-table.mce-item-table[border='0'] td,
  67. .sop-nested-table.mce-item-table[border='1'] td,
  68. .sop-nested-table.mce-item-table:not([border]) th,
  69. .sop-nested-table.mce-item-table[border='0'] th,
  70. .sop-nested-table.mce-item-table[border='1'] th {
  71. border: none !important;
  72. }
  73. .sop-nested-table > tbody > tr > td:not(:last-child) {
  74. border-right: 1px solid #334155 !important;
  75. }
  76. /* 补液等业务嵌套表:实线边框(非虚线辅助框) */
  77. .sop-grid-table,
  78. .sop-grid-table.mce-item-table,
  79. .sop-grid-table.mce-item-table:not([border]),
  80. .sop-grid-table.mce-item-table[border='0'],
  81. .sop-grid-table.mce-item-table[border='1'] {
  82. width: 100% !important;
  83. border-collapse: collapse !important;
  84. table-layout: fixed !important;
  85. margin: 8px 0 !important;
  86. border: 1px solid #334155 !important;
  87. }
  88. .sop-grid-table td,
  89. .sop-grid-table th,
  90. .sop-grid-table.mce-item-table:not([border]) td,
  91. .sop-grid-table.mce-item-table[border='0'] td,
  92. .sop-grid-table.mce-item-table[border='1'] td,
  93. .sop-grid-table.mce-item-table:not([border]) th,
  94. .sop-grid-table.mce-item-table[border='0'] th,
  95. .sop-grid-table.mce-item-table[border='1'] th {
  96. border: 1px solid #334155 !important;
  97. padding: 4px 3px !important;
  98. font-size: 9pt;
  99. vertical-align: middle;
  100. word-break: break-word;
  101. }
  102. .sop-header-table {
  103. font-size: 12pt;
  104. flex-shrink: 0;
  105. margin-bottom: 8px;
  106. }
  107. .sop-body-table {
  108. flex: 1 1 auto;
  109. height: 100%;
  110. min-height: 0;
  111. }
  112. .sop-body-table tbody {
  113. height: 100%;
  114. }
  115. .sop-body-table tr.sop-fill-row {
  116. height: 100%;
  117. }
  118. .sop-body-table td.sop-fill-cell,
  119. .sop-body-table td.sop-fill-label {
  120. height: 100%;
  121. vertical-align: middle;
  122. }
  123. .sop-header-table td {
  124. border-color: #334155;
  125. }
  126. .sop-option {
  127. display: inline-flex;
  128. align-items: flex-end;
  129. gap: 4px;
  130. margin-right: 10px;
  131. white-space: nowrap;
  132. cursor: pointer;
  133. vertical-align: text-bottom;
  134. line-height: 1.2;
  135. }
  136. .sop-option.sop-option-wrap {
  137. display: flex;
  138. flex-wrap: nowrap;
  139. align-items: flex-start;
  140. white-space: normal;
  141. max-width: 100%;
  142. margin-right: 0;
  143. vertical-align: top;
  144. }
  145. .sop-option.sop-option-wrap .sop-check {
  146. flex-shrink: 0;
  147. margin-top: 2px;
  148. top: 0;
  149. }
  150. .sop-option.sop-option-wrap .sop-option-text {
  151. flex: 1 1 auto;
  152. min-width: 0;
  153. white-space: normal;
  154. word-wrap: break-word;
  155. overflow-wrap: break-word;
  156. }
  157. .sop-option-cell .sop-option:last-child {
  158. margin-right: 0;
  159. }
  160. .sop-option-cell-wide .sop-option {
  161. margin-right: 6px;
  162. }
  163. .sop-body-table tbody td {
  164. text-align: left;
  165. }
  166. .sop-body-table tbody td[style*='text-align:center'],
  167. .sop-body-table tbody td.sop-fill-label,
  168. .sop-body-table tbody td.sop-option-cell {
  169. text-align: center;
  170. }
  171. .sop-underline,
  172. .sop-record span[style*='border-bottom:1px solid #334155'],
  173. .sop-record span[style*='border-bottom: 1px solid #334155'],
  174. .sop-blank-cell {
  175. color: #059669 !important;
  176. font-weight: 700;
  177. -webkit-print-color-adjust: exact;
  178. print-color-adjust: exact;
  179. }
  180. .sop-underline,
  181. .sop-record span[style*='border-bottom:1px solid #334155'],
  182. .sop-record span[style*='border-bottom: 1px solid #334155'] {
  183. display: inline-block;
  184. border-bottom: 1.5px solid #10b981;
  185. text-align: left !important;
  186. vertical-align: text-bottom;
  187. box-sizing: border-box;
  188. }
  189. .sop-blank-cell {
  190. text-align: left !important;
  191. vertical-align: top;
  192. }
  193. .sop-check {
  194. display: inline-block;
  195. flex-shrink: 0;
  196. width: 14px;
  197. height: 14px;
  198. border: 1.5px solid #334155;
  199. border-radius: 2px;
  200. box-sizing: border-box;
  201. background: #fff;
  202. cursor: pointer;
  203. position: relative;
  204. /* 避免内部   把基线抬到方框中部;略上移与汉字底边视觉对齐 */
  205. font-size: 0;
  206. line-height: 0;
  207. overflow: hidden;
  208. vertical-align: text-bottom;
  209. top: -3px;
  210. user-select: none;
  211. -webkit-user-select: none;
  212. }
  213. .sop-check--checked {
  214. background: #334155;
  215. -webkit-print-color-adjust: exact;
  216. print-color-adjust: exact;
  217. }
  218. .sop-check--checked::after,
  219. .sop-check[data-sop-checked='1']::after {
  220. content: '';
  221. position: absolute;
  222. left: 2px;
  223. top: 1px;
  224. width: 8px;
  225. height: 5px;
  226. border-left: 2px solid #fff;
  227. border-bottom: 2px solid #fff;
  228. transform: rotate(-45deg);
  229. }
  230. .sop-check[data-sop-checked='1'] {
  231. background: #334155;
  232. }
  233. `
  234. const editorHeightPx = getSopA4EditorHeightPx(1)
  235. const editorHeightPx2 = getSopA4EditorHeightPx(2)
  236. const printHeight2Mm = SOP_A4_HEIGHT_MM * 2
  237. /** TinyMCE 编辑区:A4 + 额外高度,无内边距裁切 */
  238. export const SOP_EDITOR_CONTENT_STYLE = `
  239. body {
  240. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB',
  241. 'Microsoft YaHei', sans-serif;
  242. font-size: 14px;
  243. line-height: 1.6;
  244. color: #334155;
  245. padding: 0;
  246. margin: 0;
  247. background: #fff;
  248. }
  249. ${SOP_SHARED_CONTENT_STYLE}
  250. .sop-record.sop-a4 {
  251. min-height: ${editorHeightPx}px;
  252. height: ${editorHeightPx}px;
  253. }
  254. .sop-record.sop-a4.sop-a4-pages-2 {
  255. min-height: ${editorHeightPx2}px;
  256. height: auto;
  257. }
  258. .sop-record.sop-a4.sop-a4-pages-2 .sop-body-table,
  259. .sop-record.sop-a4.sop-a4-pages-2 .sop-body-table tbody {
  260. flex: 0 1 auto !important;
  261. height: auto !important;
  262. }
  263. `
  264. /** 打印页样式 */
  265. export const SOP_PRINT_CONTENT_STYLE = `
  266. html {
  267. margin: 0;
  268. padding: 0;
  269. }
  270. body {
  271. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB',
  272. 'Microsoft YaHei', sans-serif;
  273. font-size: 14px;
  274. line-height: 1.6;
  275. color: #334155;
  276. padding: 0;
  277. margin: 0;
  278. background: #fff;
  279. }
  280. ${SOP_SHARED_CONTENT_STYLE}
  281. .sop-record.sop-a4 {
  282. height: ${SOP_A4_HEIGHT_MM}mm;
  283. min-height: ${SOP_A4_HEIGHT_MM}mm;
  284. max-height: ${SOP_A4_HEIGHT_MM}mm;
  285. page-break-after: avoid;
  286. page-break-inside: avoid;
  287. }
  288. .sop-record.sop-a4.sop-a4-pages-2 {
  289. height: auto;
  290. min-height: ${printHeight2Mm}mm;
  291. max-height: none;
  292. page-break-after: auto;
  293. page-break-inside: auto;
  294. }
  295. @media print {
  296. @page {
  297. size: A4 portrait;
  298. margin: 0;
  299. }
  300. html,
  301. body {
  302. width: ${SOP_A4_WIDTH_MM}mm;
  303. height: auto;
  304. min-height: ${SOP_A4_HEIGHT_MM}mm;
  305. margin: 0 !important;
  306. padding: 0 !important;
  307. overflow: visible;
  308. }
  309. .sop-record.sop-a4 {
  310. max-width: none;
  311. width: auto;
  312. margin: 0;
  313. padding: 16mm 15mm 20mm;
  314. height: ${SOP_A4_HEIGHT_MM}mm;
  315. min-height: ${SOP_A4_HEIGHT_MM}mm;
  316. max-height: ${SOP_A4_HEIGHT_MM}mm;
  317. }
  318. .sop-record.sop-a4.sop-a4-pages-2 {
  319. height: auto;
  320. min-height: ${printHeight2Mm}mm;
  321. max-height: none;
  322. page-break-inside: auto;
  323. }
  324. .sop-check {
  325. width: 3.5mm;
  326. height: 3.5mm;
  327. border-width: 0.35mm;
  328. top: -0.4mm;
  329. -webkit-print-color-adjust: exact !important;
  330. print-color-adjust: exact !important;
  331. }
  332. /* 打印用白底黑勾,不依赖“背景图形”选项 */
  333. .sop-check--checked,
  334. .sop-check[data-sop-checked='1'] {
  335. background: #fff !important;
  336. -webkit-print-color-adjust: exact !important;
  337. print-color-adjust: exact !important;
  338. }
  339. .sop-check--checked::after,
  340. .sop-check[data-sop-checked='1']::after {
  341. border-left-color: #000 !important;
  342. border-bottom-color: #000 !important;
  343. left: 0.5mm;
  344. top: 0.2mm;
  345. width: 2mm;
  346. height: 1.2mm;
  347. border-left-width: 0.4mm;
  348. border-bottom-width: 0.4mm;
  349. }
  350. }
  351. `
  352. type SopTinyMceEditor = {
  353. on: (name: string, fn: (e: Event) => void) => void
  354. getBody: () => HTMLElement
  355. getContent: (args?: { format?: string }) => string
  356. undoManager: { transact: (fn: () => void) => void }
  357. nodeChanged: () => void
  358. fire: (name: string) => void
  359. setDirty?: (state: boolean) => void
  360. }
  361. /** 规范化勾选框:避免 TinyMCE 清掉空 span,并禁止直接编辑 */
  362. export function normalizeSopCheckboxes(root: ParentNode | null | undefined): void {
  363. if (!root) return
  364. root.querySelectorAll('.sop-check').forEach((el) => {
  365. const node = el as HTMLElement
  366. node.setAttribute('contenteditable', 'false')
  367. node.setAttribute('data-mce-contenteditable', 'false')
  368. if (!node.textContent || !node.textContent.trim()) {
  369. node.innerHTML = ' '
  370. }
  371. // 用属性兜底勾选态,便于序列化与打印
  372. if (node.classList.contains('sop-check--checked')) {
  373. node.setAttribute('data-sop-checked', '1')
  374. } else if (node.getAttribute('data-sop-checked') === '1') {
  375. node.classList.add('sop-check--checked')
  376. } else {
  377. node.removeAttribute('data-sop-checked')
  378. }
  379. })
  380. }
  381. /** SOP 富文本编辑区:勾选框点击切换、选项行可点选 */
  382. export function setupSopEditorInteractions(editor: SopTinyMceEditor): void {
  383. const resolveCheckEl = (target: HTMLElement | null): HTMLElement | null => {
  384. if (!target) return null
  385. if (target.classList.contains('sop-check')) return target
  386. const option = target.closest('.sop-option')
  387. if (option) return option.querySelector('.sop-check')
  388. return null
  389. }
  390. const toggleCheck = (checkEl: HTMLElement) => {
  391. editor.undoManager.transact(() => {
  392. normalizeSopCheckboxes(checkEl.parentElement || editor.getBody())
  393. const checked = checkEl.classList.toggle('sop-check--checked')
  394. if (checked) {
  395. checkEl.setAttribute('data-sop-checked', '1')
  396. } else {
  397. checkEl.removeAttribute('data-sop-checked')
  398. }
  399. })
  400. editor.nodeChanged()
  401. editor.setDirty?.(true)
  402. // change + input,确保 tinymce-vue v-model 同步勾选后的 HTML
  403. editor.fire('change')
  404. editor.fire('input')
  405. }
  406. const handleSopClick = (e: Event) => {
  407. const target = e.target as HTMLElement | null
  408. const checkEl = resolveCheckEl(target)
  409. if (!checkEl) return
  410. e.preventDefault()
  411. e.stopPropagation()
  412. toggleCheck(checkEl)
  413. }
  414. // 仅绑定 click,避免 mousedown+click 双触发导致勾选被立刻取消
  415. editor.on('click', handleSopClick)
  416. editor.on('SetContent', () => {
  417. normalizeSopCheckboxes(editor.getBody())
  418. })
  419. normalizeSopCheckboxes(editor.getBody())
  420. }
  421. function prepareSopHtmlForPrint(html: string): string {
  422. const doc = new DOMParser().parseFromString(html, 'text/html')
  423. doc.querySelectorAll('.sop-check').forEach((el) => {
  424. const node = el as HTMLElement
  425. const checked =
  426. node.classList.contains('sop-check--checked') || node.getAttribute('data-sop-checked') === '1'
  427. if (checked) {
  428. node.classList.add('sop-check--checked')
  429. node.setAttribute('data-sop-checked', '1')
  430. } else {
  431. node.classList.remove('sop-check--checked')
  432. node.removeAttribute('data-sop-checked')
  433. }
  434. })
  435. return doc.body.innerHTML
  436. }
  437. function resolveSopHtmlAssetUrls(html: string): string {
  438. const origin = window.location.origin
  439. return html.replace(/src="\/([^"]+)"/g, `src="${origin}/$1"`)
  440. }
  441. function readBlobAsDataUrl(blob: Blob): Promise<string> {
  442. return new Promise((resolve, reject) => {
  443. const reader = new FileReader()
  444. reader.onload = () => resolve(String(reader.result || ''))
  445. reader.onerror = () => reject(reader.error || new Error('read failed'))
  446. reader.readAsDataURL(blob)
  447. })
  448. }
  449. /** 将图片转为 data URL 嵌入,避免 blob 打印页无法加载顶部 logo */
  450. async function embedSopImagesAsDataUrls(html: string): Promise<string> {
  451. const doc = new DOMParser().parseFromString(html, 'text/html')
  452. const images = Array.from(doc.querySelectorAll('img'))
  453. await Promise.all(
  454. images.map(async (img) => {
  455. const src = (img.getAttribute('src') || '').trim()
  456. if (!src || src.startsWith('data:')) return
  457. let absolute = src
  458. if (src.startsWith('/')) {
  459. absolute = `${window.location.origin}${src}`
  460. } else if (!/^https?:\/\//i.test(src)) {
  461. absolute = new URL(src, window.location.href).href
  462. }
  463. try {
  464. const res = await fetch(absolute, { credentials: 'same-origin' })
  465. if (!res.ok) throw new Error(`HTTP ${res.status}`)
  466. const blob = await res.blob()
  467. const dataUrl = await readBlobAsDataUrl(blob)
  468. if (dataUrl) {
  469. img.setAttribute('src', dataUrl)
  470. }
  471. } catch {
  472. img.setAttribute('src', absolute)
  473. }
  474. })
  475. )
  476. return doc.body.innerHTML
  477. }
  478. function buildPrintDocumentHtml(bodyHtml: string): string {
  479. return `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><title></title><style>${SOP_PRINT_CONTENT_STYLE}</style></head><body>${bodyHtml}</body></html>`
  480. }
  481. function cleanupPrintIframe(iframe: HTMLIFrameElement, blobUrl?: string) {
  482. if (iframe.parentNode) {
  483. iframe.parentNode.removeChild(iframe)
  484. }
  485. if (blobUrl) {
  486. URL.revokeObjectURL(blobUrl)
  487. }
  488. }
  489. /**
  490. * 打印 SOP 富文本(独立打印页,空标题 + blob 页减少浏览器默认页眉页脚)
  491. */
  492. export async function printSopHtml(html: string, _title = 'SOP'): Promise<void> {
  493. const content = String(html || '').trim()
  494. if (!content) {
  495. ElMessage.warning('暂无 SOP 内容可打印')
  496. return
  497. }
  498. const preparedHtml = prepareSopHtmlForPrint(content)
  499. const resolvedHtml = resolveSopHtmlAssetUrls(preparedHtml)
  500. const embeddedHtml = await embedSopImagesAsDataUrls(resolvedHtml)
  501. const printHtml = buildPrintDocumentHtml(embeddedHtml)
  502. const blob = new Blob([printHtml], { type: 'text/html' })
  503. const blobUrl = URL.createObjectURL(blob)
  504. const iframe = document.createElement('iframe')
  505. iframe.setAttribute('aria-hidden', 'true')
  506. iframe.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:none;'
  507. document.body.appendChild(iframe)
  508. const win = iframe.contentWindow
  509. if (!win) {
  510. cleanupPrintIframe(iframe, blobUrl)
  511. ElMessage.error('无法创建打印页面')
  512. return
  513. }
  514. const triggerPrint = () => {
  515. win.focus()
  516. win.print()
  517. setTimeout(() => cleanupPrintIframe(iframe, blobUrl), 1000)
  518. }
  519. iframe.onload = () => {
  520. const doc = win.document
  521. const images = Array.from(doc?.querySelectorAll('img') ?? [])
  522. if (!images.length) {
  523. triggerPrint()
  524. return
  525. }
  526. let settled = 0
  527. const onImageDone = () => {
  528. settled += 1
  529. if (settled >= images.length) {
  530. requestAnimationFrame(() => triggerPrint())
  531. }
  532. }
  533. images.forEach((img) => {
  534. if (img.complete) {
  535. onImageDone()
  536. } else {
  537. img.addEventListener('load', onImageDone)
  538. img.addEventListener('error', onImageDone)
  539. }
  540. })
  541. }
  542. iframe.onerror = () => {
  543. cleanupPrintIframe(iframe, blobUrl)
  544. ElMessage.error('无法加载打印页面')
  545. }
  546. iframe.src = blobUrl
  547. }