pdf.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import { nextTick, computed } from 'vue';
  2. import { useMainStore } from '@/store';
  3. import { ElLoading } from 'element-plus';
  4. import html2canvas from 'html2canvas';
  5. import jsPDF from 'jspdf';
  6. import { showMessage } from './common';
  7. import { uploadFile } from '@/utils/http';
  8. import { savePdf } from '@/utils/api';
  9. const mainStore = useMainStore();
  10. const expanded = computed(() => mainStore.getExpanded);
  11. const phone = computed(() => mainStore.getPhone);
  12. const recordId = computed(() => mainStore.getRecordId);
  13. const isLoadOver = computed(() => mainStore.getIsLoadOver);
  14. /**
  15. * 生成 PDF Blob
  16. */
  17. async function generatePDFBlob(
  18. pdfContent?: HTMLElement,
  19. showLoading = false
  20. ): Promise<Blob | null> {
  21. if (!isLoadOver.value) {
  22. showMessage({ type: 'warning', message: '数据加载中,请稍后再试' });
  23. return null;
  24. }
  25. let loading: any = null;
  26. if (showLoading) {
  27. loading = ElLoading.service({
  28. lock: true,
  29. text: '生成报告中...',
  30. background: 'rgba(0,0,0,0.7)'
  31. });
  32. }
  33. try {
  34. if (!pdfContent) pdfContent = document.getElementById('Record') as HTMLElement;
  35. if (!expanded.value) {
  36. mainStore.setExpanded(true);
  37. await nextTick();
  38. }
  39. await nextTick();
  40. const canvas = await html2canvas(pdfContent, {
  41. scale: 2,
  42. useCORS: true,
  43. backgroundColor: '#fff'
  44. });
  45. const canvasWidth = canvas.width;
  46. const canvasHeight = canvas.height;
  47. const pdf = new jsPDF('p', 'mm', 'a4');
  48. const pageWidth = pdf.internal.pageSize.getWidth();
  49. const pageHeight = pdf.internal.pageSize.getHeight();
  50. const ratio = pageWidth / canvasWidth;
  51. const pagePixelHeight = pageHeight / ratio;
  52. // 页边距(像素)
  53. const marginTop = 20; // 仅作用于非第一页
  54. const marginBottom = 40; // 所有页生效
  55. let positionY = 0;
  56. let pageIndex = 0;
  57. while (positionY < canvasHeight) {
  58. // 判断是否第一页
  59. const topMargin = pageIndex === 0 ? 0 : marginTop;
  60. // 每页实际可容纳的内容高度
  61. const h = Math.min(
  62. pagePixelHeight - topMargin - marginBottom,
  63. canvasHeight - positionY
  64. );
  65. const pageCanvas = document.createElement('canvas');
  66. pageCanvas.width = canvasWidth;
  67. pageCanvas.height = h;
  68. const ctx = pageCanvas.getContext('2d');
  69. ctx?.drawImage(canvas, 0, positionY, canvasWidth, h, 0, 0, canvasWidth, h);
  70. const imgData = pageCanvas.toDataURL('image/jpeg', 0.95);
  71. // 添加到 PDF 时,整体往下偏移 topMargin
  72. pdf.addImage(imgData, 'JPEG', 0, topMargin * ratio, pageWidth, h * ratio);
  73. positionY += h;
  74. pageIndex++;
  75. if (positionY < canvasHeight) pdf.addPage();
  76. }
  77. return pdf.output('blob');
  78. } catch (error) {
  79. console.error(error);
  80. showMessage({ type: 'error', message: '生成失败,请稍后再试' });
  81. return null;
  82. } finally {
  83. mainStore.setExpanded(false);
  84. setTimeout(() => loading && loading.close(), 500);
  85. }
  86. }
  87. /**
  88. * 下载文件
  89. */
  90. function triggerDownload(blob: Blob, filename = 'analysis.pdf') {
  91. const url = URL.createObjectURL(blob);
  92. const a = document.createElement('a');
  93. a.href = url;
  94. a.download = filename;
  95. a.click();
  96. URL.revokeObjectURL(url);
  97. }
  98. /**
  99. * 上传文件
  100. */
  101. async function uploadPDFFile(blob: Blob) {
  102. const file = new File([blob], 'analysis.pdf', { type: 'application/pdf' });
  103. const uploadRes = await uploadFile(file, { source: 'media', mediaType: 'file' });
  104. const pdfUrl = uploadRes.data.url;
  105. await savePdf({
  106. phone: phone.value,
  107. id: recordId.value,
  108. pdfUrl
  109. });
  110. return pdfUrl;
  111. }
  112. /**
  113. * 统一入口:生成 PDF
  114. * @param pdfContent - PDF内容DOM
  115. * @param mode - "manual" 手动下载 | "auto" 自动下载并上传
  116. */
  117. export async function handlePDF(pdfContent?: HTMLElement, mode: 'manual' | 'auto' = 'manual') {
  118. const blob = await generatePDFBlob(pdfContent, true);
  119. if (!blob) return;
  120. // 下载
  121. triggerDownload(blob);
  122. // 自动模式下再上传
  123. if (mode === 'auto') {
  124. try {
  125. await uploadPDFFile(blob);
  126. // showMessage({ type: 'success', message: '报告已下载并上传成功' });
  127. } catch (err) {
  128. // showMessage({ type: 'error', message: '报告上传失败' });
  129. throw err;
  130. }
  131. }
  132. }