exportPDF.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import html2canvas from 'html2canvas';
  2. import jsPDF from 'jspdf';
  3. import axios from 'axios'
  4. import Cookies from 'js-cookie'
  5. // export const exportPDF = async (elementId, fileName = 'document.pdf') => {
  6. export const exportPDF = async (element, fileName = 'document.pdf') => {
  7. // 获取要转换的DOM元素
  8. // const element = document.getElementById(elementId);
  9. if (!element) throw new Error('找不到目标元素');
  10. // 获取元素原始尺寸
  11. const originalWidth = element.scrollWidth;
  12. console.log(originalWidth,'originalWidth')
  13. const originalHeight = element.scrollHeight;
  14. console.log(originalHeight,'originalHeight')
  15. // 设置PDF参数
  16. const PDF_WIDTH = 210; // A4纸宽(单位:mm)
  17. const PDF_HEIGHT = 297; // A4纸高
  18. const PDF_PADDING = 10; // 页面内边距
  19. const pdf = new jsPDF('p', 'mm', 'a4');
  20. // 计算缩放比例
  21. const scale = PDF_WIDTH / originalWidth;
  22. console.log(scale,'scale')
  23. const canvasWidth = originalWidth;
  24. const canvasHeight = PDF_HEIGHT / scale;
  25. console.log(canvasHeight,'canvasHeight')
  26. // 计算总页数
  27. const pageCount = Math.ceil(originalHeight / canvasHeight);
  28. console.log(pageCount,'pageCount')
  29. // 循环渲染每一页
  30. for (let i = 0; i < pageCount; i++) {
  31. if (i > 0) pdf.addPage();
  32. // 计算当前页面的裁剪位置
  33. const canvas = await html2canvas(element, {
  34. scale: 2, // 提高分辨率
  35. scrollY: -window.scrollY,
  36. useCORS: true, // 开启跨域支持
  37. allowTaint: true, // 允许加载外部资源
  38. windowHeight: canvasHeight,
  39. y: canvasHeight * i,
  40. height: canvasHeight,
  41. width: originalWidth
  42. });
  43. if (i % 3 === 0) await new Promise(r => setTimeout(r, 200));
  44. // 将Canvas转换为图片
  45. const imgData = canvas.toDataURL('image/jpeg', 0.95);
  46. // 添加页面
  47. pdf.addImage(
  48. imgData,
  49. 'JPEG',
  50. PDF_PADDING,
  51. PDF_PADDING,
  52. PDF_WIDTH - PDF_PADDING * 2,
  53. (canvas.height * PDF_WIDTH) / canvas.width - PDF_PADDING * 2
  54. );
  55. }
  56. const pdfBlob = pdf.output('blob');
  57. const formData = new FormData();
  58. formData.append('file', pdfBlob, fileName);
  59. const response = await axios.post(
  60. `${window.SITE_CONFIG["apiURL"]}/sys/oss/uploadFile`,
  61. formData,
  62. {
  63. headers: {
  64. 'Content-Type': 'multipart/form-data',
  65. 'token': Cookies.get('token') || ''
  66. }
  67. }
  68. );
  69. return response
  70. // 保存PDF
  71. // pdf.save(fileName);
  72. };