print.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import html2canvas from 'html2canvas';
  2. import { ElMessage } from 'element-plus';
  3. /**
  4. * 打印图表
  5. * @param chartElement 图表DOM元素
  6. */
  7. export const printChart = async (chartElement: HTMLElement) => {
  8. if (!chartElement) {
  9. ElMessage.warning('图表未加载');
  10. return;
  11. }
  12. try {
  13. const canvas = await html2canvas(chartElement);
  14. const dataUrl = canvas.toDataURL('image/png');
  15. // 创建打印窗口
  16. const printWindow = window.open('', '_blank');
  17. if (!printWindow) {
  18. ElMessage.error('请允许打开新窗口');
  19. return;
  20. }
  21. printWindow.document.write(`
  22. <html>
  23. <head>
  24. <title>图表打印</title>
  25. <style>
  26. body { margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
  27. img { max-width: 100%; height: auto; }
  28. </style>
  29. </head>
  30. <body>
  31. <img src="${dataUrl}" />
  32. </body>
  33. </html>
  34. `);
  35. printWindow.document.close();
  36. // 等待图片加载完成后打印
  37. const img = printWindow.document.querySelector('img');
  38. if (img) {
  39. img.onload = () => {
  40. setTimeout(() => {
  41. printWindow.print();
  42. printWindow.close();
  43. }, 100);
  44. };
  45. }
  46. } catch (error) {
  47. console.error('打印失败:', error);
  48. ElMessage.error('打印失败,请稍后重试');
  49. }
  50. };