pdf.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. const mainStore = useMainStore();
  8. const expanded = computed(() => mainStore.getExpanded);
  9. const isLoadOver = computed(() => mainStore.getIsLoadOver);
  10. export const downloadPDF = async (pdfContent?: HTMLElement) => {
  11. if (!isLoadOver.value) {
  12. showMessage({ type: 'warning', message: '数据加载中,请稍后再试' });
  13. return;
  14. }
  15. const loading = ElLoading.service({
  16. lock: true,
  17. text: '生成中...',
  18. background: 'rgba(0,0,0,0.7)',
  19. });
  20. try {
  21. if (!pdfContent) pdfContent = document.querySelector('.record') as HTMLElement;
  22. if (!expanded.value) {
  23. mainStore.setExpanded(true);
  24. await nextTick();
  25. }
  26. await nextTick();
  27. // 高分辨率 canvas
  28. const canvas = await html2canvas(pdfContent, { scale: 2, useCORS: true, backgroundColor: '#fff' });
  29. const canvasWidth = canvas.width;
  30. const canvasHeight = canvas.height;
  31. const pdf = new jsPDF('p', 'mm', 'a4');
  32. const pageWidth = pdf.internal.pageSize.getWidth();
  33. const pageHeight = pdf.internal.pageSize.getHeight();
  34. const ratio = pageWidth / canvasWidth; // 宽度缩放比例
  35. const pagePixelHeight = pageHeight / ratio; // PDF 一页对应 canvas 的高度
  36. let positionY = 0;
  37. while (positionY < canvasHeight) {
  38. const h = Math.min(pagePixelHeight, canvasHeight - positionY);
  39. // 创建临时 canvas 截取当前页
  40. const pageCanvas = document.createElement('canvas');
  41. pageCanvas.width = canvasWidth;
  42. pageCanvas.height = h;
  43. const ctx = pageCanvas.getContext('2d');
  44. ctx?.drawImage(canvas, 0, positionY, canvasWidth, h, 0, 0, canvasWidth, h);
  45. const imgData = pageCanvas.toDataURL('image/jpeg', 0.95);
  46. pdf.addImage(imgData, 'JPEG', 0, 0, pageWidth, h * ratio);
  47. positionY += h;
  48. if (positionY < canvasHeight) pdf.addPage();
  49. }
  50. pdf.save('analysis.pdf');
  51. } catch (error) {
  52. console.error(error);
  53. showMessage({ type: 'error', message: '生成失败,请稍后再试' });
  54. } finally {
  55. mainStore.setExpanded(false);
  56. setTimeout(() => loading.close(), 500);
  57. }
  58. };