File size: 73,131 Bytes
89ce340 4822fa6 74a3356 cccb22d 89ce340 cccb22d 89ce340 74a3356 cccb22d 9b86ce9 cccb22d 9b86ce9 cccb22d 9b86ce9 cccb22d 9b86ce9 cccb22d 9b86ce9 cccb22d 9b86ce9 cccb22d 9b86ce9 cccb22d 74a3356 89ce340 74a3356 cccb22d 74a3356 89ce340 74a3356 89ce340 74a3356 89ce340 f5b4781 cccb22d f5b4781 cccb22d 9b86ce9 cccb22d 9b86ce9 cccb22d f5b4781 89ce340 f5b4781 89ce340 f184abd 89ce340 f184abd 89ce340 f184abd 89ce340 4822fa6 c69749e 4822fa6 c69749e 4822fa6 c69749e 4822fa6 c69749e 4822fa6 c69749e 4822fa6 c69749e 4822fa6 c69749e 4822fa6 c69749e f184abd 4822fa6 f184abd 9ecdcee 4822fa6 f184abd 9ecdcee 4822fa6 f184abd 9ecdcee 4822fa6 9ecdcee f184abd 9ecdcee c69749e 9ecdcee f184abd 9ecdcee 4822fa6 9ecdcee 4822fa6 9ecdcee 4822fa6 9ecdcee 4822fa6 f184abd 89ce340 4822fa6 89ce340 4822fa6 89ce340 4822fa6 89ce340 f5b4781 89ce340 f5b4781 89ce340 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 |
import { computed, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { trim } from 'lodash'
import { saveAs } from 'file-saver'
import pptxgen from 'pptxgenjs'
import tinycolor from 'tinycolor2'
import { toPng, toJpeg } from 'html-to-image'
import { useSlidesStore } from '@/store'
import type { PPTElementOutline, PPTElementShadow, PPTElementLink, Slide } from '@/types/slides'
import { getElementRange, getLineElementPath, getTableSubThemeColor } from '@/utils/element'
import { type AST, toAST } from '@/utils/htmlParser'
import { type SvgPoints, toPoints } from '@/utils/svgPathParser'
import { encrypt } from '@/utils/crypto'
import { svg2Base64 } from '@/utils/svg2Base64'
import { renderElementToBase64, isCanvasRenderSupported, getElementDimensions } from '@/utils/canvasRenderer'
import { renderWithHuggingfaceFix, isHuggingfaceEnvironment } from '@/utils/huggingfaceRenderer'
import { vectorRenderManager, RenderStrategy } from '@/utils/VectorRenderManager'
import { VECTOR_EXPORT_CONFIG } from '@/config/vectorExportConfig'
import message from '@/utils/message'
interface ExportImageConfig {
quality: number
width: number
fontEmbedCSS?: string
}
export default () => {
const slidesStore = useSlidesStore()
const { slides, theme, viewportRatio, title, viewportSize } = storeToRefs(slidesStore)
const defaultFontSize = 16
const ratioPx2Inch = computed(() => {
return 96 * (viewportSize.value / 960)
})
const ratioPx2Pt = computed(() => {
return 96 / 72 * (viewportSize.value / 960)
})
const exporting = ref(false)
// 导出图片(生产环境优化版本)
const exportImage = (domRef: HTMLElement, format: string, quality: number, ignoreWebfont = true) => {
exporting.value = true
// 环境检测
const isHF = VECTOR_EXPORT_CONFIG.ENVIRONMENT.isHuggingface()
const isProd = VECTOR_EXPORT_CONFIG.ENVIRONMENT.isProduction()
if (!isProd) {
console.log('exportImage: Environment check:', { isHuggingface: isHF, format, production: isProd })
}
// 使用VectorRenderManager预处理矢量图形元素
const preprocessVectorElements = async () => {
const svgElements = domRef.querySelectorAll('svg');
const vectorShapes = domRef.querySelectorAll('.vector-shape');
// 处理SVG元素 - 使用VectorRenderManager优化
for (const svg of Array.from(svgElements)) {
try {
const renderResult = await vectorRenderManager.renderElement(svg);
if (renderResult.success && renderResult.data) {
// 用优化后的SVG替换原始SVG
const tempDiv = document.createElement('div');
tempDiv.innerHTML = renderResult.data;
const optimizedSvg = tempDiv.querySelector('svg');
if (optimizedSvg && svg.parentNode) {
svg.parentNode.replaceChild(optimizedSvg, svg);
}
} else {
// 降级处理:手动清理属性
svg.removeAttribute('vector-effect');
const vectorEffectElements = svg.querySelectorAll('[vector-effect]');
vectorEffectElements.forEach(el => el.removeAttribute('vector-effect'));
if (!svg.hasAttribute('xmlns')) {
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
}
}
} catch (error) {
if (!isProd) {
console.warn('exportImage: VectorRenderManager failed, using fallback:', error);
}
// 降级处理
svg.removeAttribute('vector-effect');
if (!svg.hasAttribute('xmlns')) {
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
}
}
}
// 处理矢量形状 - 使用VectorRenderManager优化
for (const shape of Array.from(vectorShapes)) {
try {
const svgChild = shape.querySelector('svg');
if (svgChild) {
const renderResult = await vectorRenderManager.renderElement(svgChild);
if (renderResult.success && renderResult.data) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = renderResult.data;
const optimizedSvg = tempDiv.querySelector('svg');
if (optimizedSvg) {
svgChild.parentNode?.replaceChild(optimizedSvg, svgChild);
}
} else {
// 降级处理
svgChild.removeAttribute('vector-effect');
if (!svgChild.hasAttribute('xmlns')) {
svgChild.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
}
}
}
} catch (error) {
if (!isProd) {
console.warn('exportImage: Vector shape optimization failed:', error);
}
}
}
};
const foreignObjectSpans = domRef.querySelectorAll('foreignObject [xmlns]')
foreignObjectSpans.forEach(spanRef => spanRef.removeAttribute('xmlns'))
setTimeout(async () => {
try {
// 预处理矢量元素
await preprocessVectorElements();
let dataUrl: string
if (isHF) {
// Huggingface环境使用专用渲染器
console.log('exportImage: Using Huggingface renderer')
dataUrl = await renderWithHuggingfaceFix(domRef)
// 如果需要JPEG格式,转换PNG到JPEG
if (format === 'jpeg' && dataUrl.startsWith('data:image/png')) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const img = new Image()
await new Promise((resolve, reject) => {
img.onload = () => {
canvas.width = img.width
canvas.height = img.height
ctx?.drawImage(img, 0, 0)
dataUrl = canvas.toDataURL('image/jpeg', quality)
resolve(dataUrl)
}
img.onerror = reject
img.src = dataUrl
})
}
} else {
// 非Huggingface环境使用原有方法
const toImage = format === 'png' ? toPng : toJpeg
const config: ExportImageConfig = {
quality,
width: 1600,
}
if (ignoreWebfont) config.fontEmbedCSS = ''
dataUrl = await toImage(domRef, config)
}
exporting.value = false
saveAs(dataUrl, `${title.value}.${format}`)
if (isHF) {
message.success('图片导出成功(Huggingface优化版本)')
}
} catch (error) {
console.error('exportImage failed:', error)
exporting.value = false
if (isHF) {
message.error('图片导出失败,Huggingface环境可能存在兼容性问题')
} else {
message.error('导出图片失败')
}
}
}, 200)
}
// 导出pptist文件(特有 .pptist 后缀文件)
const exportSpecificFile = (_slides: Slide[]) => {
const blob = new Blob([encrypt(JSON.stringify(_slides))], { type: '' })
saveAs(blob, `${title.value}.pptist`)
}
// 导出JSON文件
const exportJSON = () => {
const json = {
title: title.value,
width: viewportSize.value,
height: viewportSize.value * viewportRatio.value,
theme: theme.value,
slides: slides.value,
}
const blob = new Blob([JSON.stringify(json)], { type: '' })
saveAs(blob, `${title.value}.json`)
}
// 新增:导出为HTML网页
const exportHTML = (_slides: Slide[], options: any = {}) => {
exporting.value = true
try {
const {
includeInteractivity = false,
standalone = true,
includeCSS = true
} = options
// 生成HTML内容
const htmlContent = generateHTMLPresentation(_slides, {
title: title.value,
theme: theme.value,
viewportSize: viewportSize.value,
viewportRatio: viewportRatio.value,
includeInteractivity,
standalone,
includeCSS
})
// 创建并下载HTML文件
const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' })
saveAs(blob, `${title.value}.html`)
message.success('HTML网页导出成功')
}
catch (error: any) {
message.error('HTML网页导出失败')
}
finally {
exporting.value = false
}
}
// 生成完整的HTML演示文稿
const generateHTMLPresentation = (slides: Slide[], config: any) => {
const { title, theme, viewportSize, viewportRatio, includeInteractivity, includeCSS } = config
const slideHeight = Math.round(viewportSize * viewportRatio)
// CSS样式
const css = includeCSS ? `
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: '${theme.fontName}', 'Microsoft YaHei', Arial, sans-serif;
background: ${theme.backgroundColor};
color: ${theme.fontColor};
overflow: hidden;
}
.presentation-container {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: #000;
}
.slide-container {
width: ${viewportSize}px;
height: ${slideHeight}px;
background: #fff;
position: relative;
overflow: hidden;
transform-origin: center;
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
}
.slide {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
display: none;
}
.slide.active {
display: block;
}
.element {
position: absolute;
word-wrap: break-word;
}
.text-element {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
.image-element img {
width: 100%;
height: 100%;
object-fit: contain;
}
.shape-element {
border-radius: var(--border-radius, 0);
}
.navigation {
position: fixed;
bottom: 30px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 10px;
z-index: 1000;
}
.nav-btn {
padding: 12px 20px;
background: rgba(255,255,255,0.9);
border: none;
border-radius: 25px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.nav-btn:hover {
background: rgba(255,255,255,1);
transform: translateY(-2px);
}
.nav-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.slide-counter {
position: fixed;
top: 30px;
right: 30px;
background: rgba(0,0,0,0.7);
color: white;
padding: 8px 16px;
border-radius: 20px;
font-size: 14px;
z-index: 1000;
}
.fullscreen-btn {
position: fixed;
top: 30px;
left: 30px;
background: rgba(0,0,0,0.7);
color: white;
border: none;
padding: 8px 16px;
border-radius: 20px;
cursor: pointer;
font-size: 14px;
z-index: 1000;
}
/* 响应式缩放 */
@media (max-width: 1200px) {
.slide-container {
transform: scale(0.8);
}
}
@media (max-width: 800px) {
.slide-container {
transform: scale(0.6);
}
}
@media (max-width: 600px) {
.slide-container {
transform: scale(0.4);
}
}
</style>
` : ''
// JavaScript交互功能
const javascript = includeInteractivity ? `
<script>
class PPTViewer {
constructor() {
this.currentSlide = 0;
this.totalSlides = ${slides.length};
this.init();
}
init() {
this.updateSlide();
this.bindEvents();
this.autoScale();
window.addEventListener('resize', () => this.autoScale());
}
bindEvents() {
document.addEventListener('keydown', (e) => {
switch(e.key) {
case 'ArrowLeft':
case 'ArrowUp':
this.prevSlide();
break;
case 'ArrowRight':
case 'ArrowDown':
case ' ':
this.nextSlide();
break;
case 'Home':
this.goToSlide(0);
break;
case 'End':
this.goToSlide(this.totalSlides - 1);
break;
case 'F11':
this.toggleFullscreen();
break;
}
});
}
nextSlide() {
if (this.currentSlide < this.totalSlides - 1) {
this.currentSlide++;
this.updateSlide();
}
}
prevSlide() {
if (this.currentSlide > 0) {
this.currentSlide--;
this.updateSlide();
}
}
goToSlide(index) {
if (index >= 0 && index < this.totalSlides) {
this.currentSlide = index;
this.updateSlide();
}
}
updateSlide() {
// 隐藏所有幻灯片
document.querySelectorAll('.slide').forEach(slide => {
slide.classList.remove('active');
});
// 显示当前幻灯片
const currentSlideEl = document.getElementById('slide-' + this.currentSlide);
if (currentSlideEl) {
currentSlideEl.classList.add('active');
}
// 更新计数器
const counter = document.querySelector('.slide-counter');
if (counter) {
counter.textContent = \`\${this.currentSlide + 1} / \${this.totalSlides}\`;
}
// 更新导航按钮状态
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
if (prevBtn) prevBtn.disabled = this.currentSlide === 0;
if (nextBtn) nextBtn.disabled = this.currentSlide === this.totalSlides - 1;
}
autoScale() {
const container = document.querySelector('.slide-container');
if (!container) return;
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const slideWidth = ${viewportSize};
const slideHeight = ${slideHeight};
const scaleX = (windowWidth * 0.9) / slideWidth;
const scaleY = (windowHeight * 0.9) / slideHeight;
const scale = Math.min(scaleX, scaleY, 1);
container.style.transform = \`scale(\${scale})\`;
}
toggleFullscreen() {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
} else {
document.exitFullscreen();
}
}
}
// 初始化PPT查看器
document.addEventListener('DOMContentLoaded', () => {
new PPTViewer();
});
</script>
` : ''
// 生成幻灯片HTML
const slidesHTML = slides.map((slide, index) => {
const slideBackground = formatSlideBackground(slide.background)
const elementsHTML = slide.elements.map(element => formatElement(element)).join('')
return `
<div id="slide-${index}" class="slide ${index === 0 ? 'active' : ''}" style="${slideBackground}">
${elementsHTML}
</div>
`
}).join('')
// 导航控件HTML
const navigationHTML = includeInteractivity ? `
<div class="navigation">
<button id="prevBtn" class="nav-btn" onclick="window.pptViewer?.prevSlide()">上一页</button>
<button id="nextBtn" class="nav-btn" onclick="window.pptViewer?.nextSlide()">下一页</button>
</div>
<div class="slide-counter">1 / ${slides.length}</div>
<button class="fullscreen-btn" onclick="window.pptViewer?.toggleFullscreen()">全屏</button>
` : ''
// 组装完整HTML
const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>
<meta name="description" content="PPTist导出的HTML演示文稿">
<meta name="generator" content="PPTist">
${css}
</head>
<body>
<div class="presentation-container">
<div class="slide-container">
${slidesHTML}
</div>
</div>
${navigationHTML}
${javascript}
</body>
</html>`
return html
}
// 格式化幻灯片背景
const formatSlideBackground = (background: any) => {
if (!background) {
return 'background: #ffffff;'
}
if (background.type === 'solid') {
return `background: ${background.color || '#ffffff'};`
}
if (background.type === 'gradient') {
const { gradientType, colors } = background
if (gradientType === 'linear') {
return `background: linear-gradient(${background.gradientRotate || 0}deg, ${colors.map((c: any) => c.color).join(', ')});`
}
return `background: radial-gradient(${colors.map((c: any) => c.color).join(', ')});`
}
if (background.type === 'image' && background.image) {
return `background-image: url(${background.image.src}); background-size: cover; background-position: center;`
}
return 'background: #ffffff;'
}
// 格式化元素
// 生产环境级别的矢量图形SVG生成函数
const generateSVGFromShape = (element: any): string => {
try {
const { width, height, path, fill, outline, viewBox, opacity = 1 } = element;
const [vbX, vbY, vbWidth, vbHeight] = viewBox || [0, 0, width, height];
// 安全的颜色处理
const fillColor = fill || '#000000';
const strokeColor = outline?.color || 'none';
const strokeWidth = outline?.width || 0;
// 构建SVG字符串,确保所有属性都被正确转义
const svgAttributes = [
`width="${width}"`,
`height="${height}"`,
`viewBox="${vbX} ${vbY} ${vbWidth} ${vbHeight}"`,
'xmlns="http://www.w3.org/2000/svg"',
'style="display: block; width: 100%; height: 100%;"'
].join(' ');
const pathAttributes = [
`d="${path}"`,
`fill="${fillColor}"`,
strokeWidth > 0 ? `stroke="${strokeColor}"` : '',
strokeWidth > 0 ? `stroke-width="${strokeWidth}"` : '',
opacity < 1 ? `opacity="${opacity}"` : '',
'vector-effect="non-scaling-stroke"'
].filter(Boolean).join(' ');
return `<svg ${svgAttributes}><path ${pathAttributes} /></svg>`;
} catch (error) {
console.error('generateSVGFromShape error:', error);
// 生产环境降级处理:返回简单的占位符
return `<svg width="${element.width || 100}" height="${element.height || 100}" xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="#f5f5f5" stroke="#ddd" stroke-width="1"/>
<text x="50%" y="50%" text-anchor="middle" dy="0.3em" font-size="12" fill="#999">Vector</text>
</svg>`;
}
};
const formatElement = (element: any) => {
const baseStyle = `
left: ${element.left || 0}px;
top: ${element.top || 0}px;
width: ${element.width || 100}px;
height: ${element.height || 100}px;
transform: rotate(${element.rotate || 0}deg);
`
if (element.type === 'text') {
const textStyle = `
font-size: ${element.fontSize || 16}px;
font-family: ${element.fontName || 'Microsoft YaHei'};
color: ${element.color || '#000000'};
font-weight: ${element.bold ? 'bold' : 'normal'};
font-style: ${element.italic ? 'italic' : 'normal'};
text-decoration: ${element.underline ? 'underline' : 'none'};
text-align: ${element.align || 'left'};
line-height: ${element.lineHeight || 1.5};
`
return `<div class="element text-element" style="${baseStyle}${textStyle}">${element.content || ''}</div>`
}
if (element.type === 'image' && element.src) {
return `<div class="element image-element" style="${baseStyle}"><img src="${element.src}" alt="图片" /></div>`
}
if (element.type === 'shape') {
// 处理特殊矢量图形(生产环境优化)
if (element.special && element.path) {
try {
const svgContent = generateSVGFromShape(element);
// 使用VectorRenderManager进一步优化SVG
const tempDiv = document.createElement('div');
tempDiv.innerHTML = svgContent;
const svgElement = tempDiv.querySelector('svg');
if (svgElement) {
// 异步优化SVG(不阻塞主流程)
vectorRenderManager.renderElement(svgElement).then(result => {
if (result.success && result.data) {
// 在后台优化成功,但不影响当前渲染
if (!VECTOR_EXPORT_CONFIG.ENVIRONMENT.isProduction()) {
console.log('formatElement: SVG optimized successfully');
}
}
}).catch(error => {
if (!VECTOR_EXPORT_CONFIG.ENVIRONMENT.isProduction()) {
console.warn('formatElement: Background SVG optimization failed:', error);
}
});
}
return `<div class="element shape-element vector-shape" style="${baseStyle}">${svgContent}</div>`;
} catch (error) {
// 生产环境降级处理
if (VECTOR_EXPORT_CONFIG.ERROR_CONFIG.LOGGING.VERBOSE) {
console.warn('formatElement: Vector shape generation failed, using fallback:', error);
}
// 使用VectorRenderManager生成优化的降级SVG
try {
const placeholderElement = document.createElement('div');
placeholderElement.style.width = `${element.width}px`;
placeholderElement.style.height = `${element.height}px`;
// 尝试使用VectorRenderManager生成占位符
vectorRenderManager.renderElement(placeholderElement).then(result => {
if (result.success && result.data) {
// 异步替换占位符(不阻塞当前渲染)
if (!VECTOR_EXPORT_CONFIG.ENVIRONMENT.isProduction()) {
console.log('formatElement: Fallback SVG generated successfully');
}
}
}).catch(() => {
// 静默处理降级失败
});
} catch (managerError) {
// VectorRenderManager也失败时的最终降级
}
// 使用简化的矢量图形表示
const fallbackSvg = `<svg width="${element.width}" height="${element.height}" xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="${element.fill || '#f5f5f5'}" stroke="${element.outline?.color || '#ddd'}" stroke-width="${element.outline?.width || 1}"/>
<text x="50%" y="50%" text-anchor="middle" dy="0.3em" font-size="12" fill="#999">Vector</text>
</svg>`;
return `<div class="element shape-element vector-shape-fallback" style="${baseStyle}">${fallbackSvg}</div>`;
}
}
// 处理普通形状
const shapeStyle = `
background: ${element.fill || '#ffffff'};
border: ${element.outline?.width || 0}px solid ${element.outline?.color || '#000000'};
border-radius: ${element.borderRadius || 0}px;
`
return `<div class="element shape-element" style="${baseStyle}${shapeStyle}"></div>`
}
// 其他元素类型的基本处理
return `<div class="element" style="${baseStyle}"></div>`
}
// 格式化颜色值为 透明度 + HexString,供pptxgenjs使用
const formatColor = (_color: string) => {
if (!_color) {
return {
alpha: 0,
color: '#000000',
}
}
const c = tinycolor(_color)
const alpha = c.getAlpha()
const color = alpha === 0 ? '#ffffff' : c.setAlpha(1).toHexString()
return {
alpha,
color,
}
}
type FormatColor = ReturnType<typeof formatColor>
// 将HTML字符串格式化为pptxgenjs所需的格式
// 核心思路:将HTML字符串按样式分片平铺,每个片段需要继承祖先元素的样式信息,遇到块级元素需要换行
const formatHTML = (html: string) => {
const ast = toAST(html)
let bulletFlag = false
let indent = 0
const slices: pptxgen.TextProps[] = []
const parse = (obj: AST[], baseStyleObj: { [key: string]: string } = {}) => {
for (const item of obj) {
const isBlockTag = 'tagName' in item && ['div', 'li', 'p'].includes(item.tagName)
if (isBlockTag && slices.length) {
const lastSlice = slices[slices.length - 1]
if (!lastSlice.options) lastSlice.options = {}
lastSlice.options.breakLine = true
}
const styleObj = { ...baseStyleObj }
const styleAttr = 'attributes' in item ? item.attributes.find(attr => attr.key === 'style') : null
if (styleAttr && styleAttr.value) {
const styleArr = styleAttr.value.split(';')
for (const styleItem of styleArr) {
const [_key, _value] = styleItem.split(': ')
const [key, value] = [trim(_key), trim(_value)]
if (key && value) styleObj[key] = value
}
}
if ('tagName' in item) {
if (item.tagName === 'em') {
styleObj['font-style'] = 'italic'
}
if (item.tagName === 'strong') {
styleObj['font-weight'] = 'bold'
}
if (item.tagName === 'sup') {
styleObj['vertical-align'] = 'super'
}
if (item.tagName === 'sub') {
styleObj['vertical-align'] = 'sub'
}
if (item.tagName === 'a') {
const attr = item.attributes.find(attr => attr.key === 'href')
styleObj['href'] = attr?.value || ''
}
if (item.tagName === 'ul') {
styleObj['list-type'] = 'ul'
}
if (item.tagName === 'ol') {
styleObj['list-type'] = 'ol'
}
if (item.tagName === 'li') {
bulletFlag = true
}
if (item.tagName === 'p') {
if ('attributes' in item) {
const dataIndentAttr = item.attributes.find(attr => attr.key === 'data-indent')
if (dataIndentAttr && dataIndentAttr.value) indent = +dataIndentAttr.value
}
}
}
if ('tagName' in item && item.tagName === 'br') {
slices.push({ text: '', options: { breakLine: true } })
}
else if ('content' in item) {
const text = item.content.replace(/ /g, ' ').replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&').replace(/\n/g, '')
const options: pptxgen.TextPropsOptions = {}
if (styleObj['font-size']) {
options.fontSize = parseInt(styleObj['font-size']) / ratioPx2Pt.value
}
if (styleObj['color']) {
options.color = formatColor(styleObj['color']).color
}
if (styleObj['background-color']) {
options.highlight = formatColor(styleObj['background-color']).color
}
if (styleObj['text-decoration-line']) {
if (styleObj['text-decoration-line'].indexOf('underline') !== -1) {
options.underline = {
color: options.color || '#000000',
style: 'sng',
}
}
if (styleObj['text-decoration-line'].indexOf('line-through') !== -1) {
options.strike = 'sngStrike'
}
}
if (styleObj['text-decoration']) {
if (styleObj['text-decoration'].indexOf('underline') !== -1) {
options.underline = {
color: options.color || '#000000',
style: 'sng',
}
}
if (styleObj['text-decoration'].indexOf('line-through') !== -1) {
options.strike = 'sngStrike'
}
}
if (styleObj['vertical-align']) {
if (styleObj['vertical-align'] === 'super') options.superscript = true
if (styleObj['vertical-align'] === 'sub') options.subscript = true
}
if (styleObj['text-align']) options.align = styleObj['text-align'] as pptxgen.HAlign
if (styleObj['font-weight']) options.bold = styleObj['font-weight'] === 'bold'
if (styleObj['font-style']) options.italic = styleObj['font-style'] === 'italic'
if (styleObj['font-family']) options.fontFace = styleObj['font-family']
if (styleObj['href']) options.hyperlink = { url: styleObj['href'] }
if (bulletFlag && styleObj['list-type'] === 'ol') {
options.bullet = { type: 'number', indent: (options.fontSize || defaultFontSize) * 1.25 }
options.paraSpaceBefore = 0.1
bulletFlag = false
}
if (bulletFlag && styleObj['list-type'] === 'ul') {
options.bullet = { indent: (options.fontSize || defaultFontSize) * 1.25 }
options.paraSpaceBefore = 0.1
bulletFlag = false
}
if (indent) {
options.indentLevel = indent
indent = 0
}
slices.push({ text, options })
}
else if ('children' in item) parse(item.children, styleObj)
}
}
parse(ast)
return slices
}
type Points = Array<
| { x: number; y: number; moveTo?: boolean }
| { x: number; y: number; curve: { type: 'arc'; hR: number; wR: number; stAng: number; swAng: number } }
| { x: number; y: number; curve: { type: 'quadratic'; x1: number; y1: number } }
| { x: number; y: number; curve: { type: 'cubic'; x1: number; y1: number; x2: number; y2: number } }
| { close: true }
>
// 将SVG路径信息格式化为pptxgenjs所需要的格式
const formatPoints = (points: SvgPoints, scale = { x: 1, y: 1 }): Points => {
return points.map(point => {
if (point.close !== undefined) {
return { close: true }
}
else if (point.type === 'M') {
return {
x: point.x / ratioPx2Inch.value * scale.x,
y: point.y / ratioPx2Inch.value * scale.y,
moveTo: true,
}
}
else if (point.curve) {
if (point.curve.type === 'cubic') {
return {
x: point.x / ratioPx2Inch.value * scale.x,
y: point.y / ratioPx2Inch.value * scale.y,
curve: {
type: 'cubic',
x1: (point.curve.x1 as number) / ratioPx2Inch.value * scale.x,
y1: (point.curve.y1 as number) / ratioPx2Inch.value * scale.y,
x2: (point.curve.x2 as number) / ratioPx2Inch.value * scale.x,
y2: (point.curve.y2 as number) / ratioPx2Inch.value * scale.y,
},
}
}
else if (point.curve.type === 'quadratic') {
return {
x: point.x / ratioPx2Inch.value * scale.x,
y: point.y / ratioPx2Inch.value * scale.y,
curve: {
type: 'quadratic',
x1: (point.curve.x1 as number) / ratioPx2Inch.value * scale.x,
y1: (point.curve.y1 as number) / ratioPx2Inch.value * scale.y,
},
}
}
}
return {
x: point.x / ratioPx2Inch.value * scale.x,
y: point.y / ratioPx2Inch.value * scale.y,
}
})
}
// 获取阴影配置
const getShadowOption = (shadow: PPTElementShadow): pptxgen.ShadowProps => {
const c = formatColor(shadow.color)
const { h, v } = shadow
let offset = 4
let angle = 45
if (h === 0 && v === 0) {
offset = 4
angle = 45
}
else if (h === 0) {
if (v > 0) {
offset = v
angle = 90
}
else {
offset = -v
angle = 270
}
}
else if (v === 0) {
if (h > 0) {
offset = h
angle = 1
}
else {
offset = -h
angle = 180
}
}
else if (h > 0 && v > 0) {
offset = Math.max(h, v)
angle = 45
}
else if (h > 0 && v < 0) {
offset = Math.max(h, -v)
angle = 315
}
else if (h < 0 && v > 0) {
offset = Math.max(-h, v)
angle = 135
}
else if (h < 0 && v < 0) {
offset = Math.max(-h, -v)
angle = 225
}
return {
type: 'outer',
color: c.color.replace('#', ''),
opacity: c.alpha,
blur: shadow.blur / ratioPx2Pt.value,
offset,
angle,
}
}
const dashTypeMap = {
'solid': 'solid',
'dashed': 'dash',
'dotted': 'sysDot',
}
// 获取边框配置
const getOutlineOption = (outline: PPTElementOutline): pptxgen.ShapeLineProps => {
const c = formatColor(outline?.color || '#000000')
return {
color: c.color,
transparency: (1 - c.alpha) * 100,
width: (outline.width || 1) / ratioPx2Pt.value,
dashType: outline.style ? dashTypeMap[outline.style] as 'solid' | 'dash' | 'sysDot' : 'solid',
}
}
// 获取超链接配置
const getLinkOption = (link: PPTElementLink): pptxgen.HyperlinkProps | null => {
const { type, target } = link
if (type === 'web') return { url: target }
if (type === 'slide') {
const index = slides.value.findIndex(slide => slide.id === target)
if (index !== -1) return { slide: index + 1 }
}
return null
}
// 判断是否为Base64图片地址
const isBase64Image = (url: string) => {
const regex = /^data:image\/[^;]+;base64,/
return url.match(regex) !== null
}
// 判断是否为SVG图片地址
const isSVGImage = (url: string) => {
const isSVGBase64 = /^data:image\/svg\+xml;base64,/.test(url)
const isSVGUrl = /\.svg$/.test(url)
return isSVGBase64 || isSVGUrl
}
// 确保元素已渲染的辅助函数
const ensureElementsRendered = async () => {
return new Promise<void>((resolve) => {
// 强制重绘
document.body.offsetHeight;
// 等待下一个动画帧
requestAnimationFrame(() => {
requestAnimationFrame(() => {
resolve();
});
});
});
};
// 导出PPTX文件
const exportPPTX = async (_slides: Slide[], masterOverwrite: boolean, ignoreMedia: boolean) => {
exporting.value = true
try {
// 确保所有元素已渲染
await ensureElementsRendered();
} catch (error) {
console.warn('Failed to ensure elements rendered:', error);
}
const pptx = new pptxgen()
if (viewportRatio.value === 0.625) pptx.layout = 'LAYOUT_16x10'
else if (viewportRatio.value === 0.75) pptx.layout = 'LAYOUT_4x3'
else if (viewportRatio.value === 0.70710678) {
pptx.defineLayout({ name: 'A3', width: 10, height: 7.0710678 })
pptx.layout = 'A3'
}
else if (viewportRatio.value === 1.41421356) {
pptx.defineLayout({ name: 'A3_V', width: 10, height: 14.1421356 })
pptx.layout = 'A3_V'
}
else pptx.layout = 'LAYOUT_16x9'
if (masterOverwrite) {
const { color: bgColor, alpha: bgAlpha } = formatColor(theme.value.backgroundColor)
pptx.defineSlideMaster({
title: 'PPTIST_MASTER',
background: { color: bgColor, transparency: (1 - bgAlpha) * 100 },
})
}
for (const slide of _slides) {
const pptxSlide = pptx.addSlide()
if (slide.background) {
const background = slide.background
if (background.type === 'image' && background.image) {
if (isSVGImage(background.image.src)) {
pptxSlide.addImage({
data: background.image.src,
x: 0,
y: 0,
w: viewportSize.value / ratioPx2Inch.value,
h: viewportSize.value * viewportRatio.value / ratioPx2Inch.value,
})
}
else if (isBase64Image(background.image.src)) {
pptxSlide.background = { data: background.image.src }
}
else {
pptxSlide.background = { path: background.image.src }
}
}
else if (background.type === 'solid' && background.color) {
const c = formatColor(background.color)
pptxSlide.background = { color: c.color, transparency: (1 - c.alpha) * 100 }
}
else if (background.type === 'gradient' && background.gradient) {
const colors = background.gradient.colors
const color1 = colors[0].color
const color2 = colors[colors.length - 1].color
const color = tinycolor.mix(color1, color2).toHexString()
const c = formatColor(color)
pptxSlide.background = { color: c.color, transparency: (1 - c.alpha) * 100 }
}
}
if (slide.remark) {
const doc = new DOMParser().parseFromString(slide.remark, 'text/html')
const pList = doc.body.querySelectorAll('p')
const text = []
for (const p of pList) {
const textContent = p.textContent
text.push(textContent || '')
}
pptxSlide.addNotes(text.join('\n'))
}
if (!slide.elements) continue
for (const el of slide.elements) {
if (el.type === 'text') {
const textProps = formatHTML(el.content)
const options: pptxgen.TextPropsOptions = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
fontSize: defaultFontSize / ratioPx2Pt.value,
fontFace: '微软雅黑',
color: '#000000',
valign: 'top',
margin: 10 / ratioPx2Pt.value,
paraSpaceBefore: 5 / ratioPx2Pt.value,
lineSpacingMultiple: 1.5 / 1.25,
autoFit: true,
}
if (el.rotate) options.rotate = el.rotate
if (el.wordSpace) options.charSpacing = el.wordSpace / ratioPx2Pt.value
if (el.lineHeight) options.lineSpacingMultiple = el.lineHeight / 1.25
if (el.fill) {
const c = formatColor(el.fill)
const opacity = el.opacity === undefined ? 1 : el.opacity
options.fill = { color: c.color, transparency: (1 - c.alpha * opacity) * 100 }
}
if (el.defaultColor) options.color = formatColor(el.defaultColor).color
if (el.defaultFontName) options.fontFace = el.defaultFontName
if (el.shadow) options.shadow = getShadowOption(el.shadow)
if (el.outline?.width) options.line = getOutlineOption(el.outline)
if (el.opacity !== undefined) options.transparency = (1 - el.opacity) * 100
if (el.paragraphSpace !== undefined) options.paraSpaceBefore = el.paragraphSpace / ratioPx2Pt.value
if (el.vertical) options.vert = 'eaVert'
pptxSlide.addText(textProps, options)
}
else if (el.type === 'image') {
const options: pptxgen.ImageProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
}
if (isBase64Image(el.src)) options.data = el.src
else options.path = el.src
if (el.flipH) options.flipH = el.flipH
if (el.flipV) options.flipV = el.flipV
if (el.rotate) options.rotate = el.rotate
if (el.link) {
const linkOption = getLinkOption(el.link)
if (linkOption) options.hyperlink = linkOption
}
if (el.filters?.opacity) options.transparency = 100 - parseInt(el.filters?.opacity)
if (el.clip) {
if (el.clip.shape === 'ellipse') options.rounding = true
const [start, end] = el.clip.range
const [startX, startY] = start
const [endX, endY] = end
const originW = el.width / ((endX - startX) / ratioPx2Inch.value)
const originH = el.height / ((endY - startY) / ratioPx2Inch.value)
options.w = originW / ratioPx2Inch.value
options.h = originH / ratioPx2Inch.value
options.sizing = {
type: 'crop',
x: startX / ratioPx2Inch.value * originW / ratioPx2Inch.value,
y: startY / ratioPx2Inch.value * originH / ratioPx2Inch.value,
w: (endX - startX) / ratioPx2Inch.value * originW / ratioPx2Inch.value,
h: (endY - startY) / ratioPx2Inch.value * originH / ratioPx2Inch.value,
}
}
pptxSlide.addImage(options)
}
else if (el.type === 'shape') {
if (el.special) {
console.log(`Processing special shape ${el.id} with Canvas rendering:`, {
type: el.type,
special: el.special,
width: el.width,
height: el.height,
left: el.left,
top: el.top
});
// 检查Canvas渲染支持
if (!isCanvasRenderSupported()) {
console.warn('Canvas rendering not supported, falling back to path-based export');
// 降级到普通形状处理的代码保持不变
const scale = {
x: el.width / el.viewBox[0],
y: el.height / el.viewBox[1],
};
const points = formatPoints(toPoints(el.path), scale);
let fillColor = formatColor(el.fill);
if (el.gradient) {
const colors = el.gradient.colors;
const color1 = colors[0].color;
const color2 = colors[colors.length - 1].color;
const color = tinycolor.mix(color1, color2).toHexString();
fillColor = formatColor(color);
}
if (el.pattern) fillColor = formatColor('#00000000');
const opacity = el.opacity === undefined ? 1 : el.opacity;
const fallbackOptions: pptxgen.ShapeProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
fill: { color: fillColor.color, transparency: (1 - fillColor.alpha * opacity) * 100 },
points,
};
if (el.flipH) fallbackOptions.flipH = el.flipH;
if (el.flipV) fallbackOptions.flipV = el.flipV;
if (el.shadow) fallbackOptions.shadow = getShadowOption(el.shadow);
if (el.outline?.width) fallbackOptions.line = getOutlineOption(el.outline);
if (el.rotate) fallbackOptions.rotate = el.rotate;
if (el.link) {
const linkOption = getLinkOption(el.link);
if (linkOption) fallbackOptions.hyperlink = linkOption;
}
pptxSlide.addShape('custGeom' as pptxgen.ShapeType, fallbackOptions);
continue;
}
// 尝试多种选择器策略查找元素
let targetElement: HTMLElement | null = null;
// 优先查找包含SVG的容器元素
const containerSelectors = [
`.thumbnail-list .base-element-${el.id}`,
`[data-element-id="${el.id}"]`,
`#element-${el.id}`,
`[class*="${el.id}"]`
];
for (const selector of containerSelectors) {
const container = document.querySelector(selector) as HTMLElement;
if (container) {
// 检查容器是否包含SVG
const svgInContainer = container.querySelector('svg');
if (svgInContainer) {
targetElement = container;
console.log(`Found container with SVG for ${el.id} using selector: ${selector}`);
break;
}
// 如果容器本身就是我们要的元素
if (container.tagName.toLowerCase() === 'svg' || container.children.length > 0) {
targetElement = container;
console.log(`Found target element for ${el.id} using selector: ${selector}`);
break;
}
}
}
// 如果没找到容器,直接查找SVG元素
if (!targetElement) {
const svgSelectors = [
`.thumbnail-list .base-element-${el.id} svg`,
`[data-element-id="${el.id}"] svg`,
`#element-${el.id} svg`
];
for (const selector of svgSelectors) {
const svgElement = document.querySelector(selector) as HTMLElement;
if (svgElement) {
targetElement = svgElement;
console.log(`Found SVG element for ${el.id} using selector: ${selector}`);
break;
}
}
}
// 最后尝试通过父元素匹配查找
if (!targetElement) {
const allSvgs = document.querySelectorAll('svg');
console.log(`Searching through ${allSvgs.length} SVG elements for ${el.id}`);
for (const svg of allSvgs) {
const parent = svg.closest(`[class*="${el.id}"]`);
if (parent) {
targetElement = svg as HTMLElement;
console.log(`Found SVG for ${el.id} using parent matching`);
break;
}
}
}
if (!targetElement) {
console.warn(`No target element found for shape ${el.id}, falling back to path-based export`);
// 降级处理代码...
const scale = {
x: el.width / el.viewBox[0],
y: el.height / el.viewBox[1],
};
const points = formatPoints(toPoints(el.path), scale);
let fillColor = formatColor(el.fill);
if (el.gradient) {
const colors = el.gradient.colors;
const color1 = colors[0].color;
const color2 = colors[colors.length - 1].color;
const color = tinycolor.mix(color1, color2).toHexString();
fillColor = formatColor(color);
}
if (el.pattern) fillColor = formatColor('#00000000');
const opacity = el.opacity === undefined ? 1 : el.opacity;
const fallbackOptions: pptxgen.ShapeProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
fill: { color: fillColor.color, transparency: (1 - fillColor.alpha * opacity) * 100 },
points,
};
if (el.flipH) fallbackOptions.flipH = el.flipH;
if (el.flipV) fallbackOptions.flipV = el.flipV;
if (el.shadow) fallbackOptions.shadow = getShadowOption(el.shadow);
if (el.outline?.width) fallbackOptions.line = getOutlineOption(el.outline);
if (el.rotate) fallbackOptions.rotate = el.rotate;
if (el.link) {
const linkOption = getLinkOption(el.link);
if (linkOption) fallbackOptions.hyperlink = linkOption;
}
pptxSlide.addShape('custGeom' as pptxgen.ShapeType, fallbackOptions);
continue;
}
// 检查元素尺寸 - 使用更智能的检查逻辑
const dimensions = getElementDimensions(targetElement);
console.log(`Target element dimensions for ${el.id}:`, dimensions);
// 更宽松的尺寸检查:只要有任何一种尺寸测量方法返回有效值就继续
const hasValidDimensions = (
dimensions.width > 0 || dimensions.height > 0 ||
dimensions.clientWidth > 0 || dimensions.clientHeight > 0 ||
dimensions.offsetWidth > 0 || dimensions.offsetHeight > 0 ||
dimensions.boundingRect.width > 0 || dimensions.boundingRect.height > 0
);
if (!hasValidDimensions) {
console.warn(`No valid dimensions found for shape ${el.id}:`, dimensions);
console.log('Falling back to path-based export');
// 降级处理代码...
const scale = {
x: el.width / el.viewBox[0],
y: el.height / el.viewBox[1],
};
const points = formatPoints(toPoints(el.path), scale);
let fillColor = formatColor(el.fill);
if (el.gradient) {
const colors = el.gradient.colors;
const color1 = colors[0].color;
const color2 = colors[colors.length - 1].color;
const color = tinycolor.mix(color1, color2).toHexString();
fillColor = formatColor(color);
}
if (el.pattern) fillColor = formatColor('#00000000');
const opacity = el.opacity === undefined ? 1 : el.opacity;
const fallbackOptions: pptxgen.ShapeProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
fill: { color: fillColor.color, transparency: (1 - fillColor.alpha * opacity) * 100 },
points,
};
if (el.flipH) fallbackOptions.flipH = el.flipH;
if (el.flipV) fallbackOptions.flipV = el.flipV;
if (el.shadow) fallbackOptions.shadow = getShadowOption(el.shadow);
if (el.outline?.width) fallbackOptions.line = getOutlineOption(el.outline);
if (el.rotate) fallbackOptions.rotate = el.rotate;
if (el.link) {
const linkOption = getLinkOption(el.link);
if (linkOption) fallbackOptions.hyperlink = linkOption;
}
pptxSlide.addShape('custGeom' as pptxgen.ShapeType, fallbackOptions);
continue;
}
// 使用多重策略渲染矢量图形
let base64Image;
let renderSuccess = false;
// 策略1: 优先使用SVG序列化(对矢量图形更可靠)
try {
console.log(`Attempting SVG serialization for ${el.id}`);
const svgElement = targetElement.tagName.toLowerCase() === 'svg'
? targetElement
: targetElement.querySelector('svg');
if (svgElement) {
// 确保SVG元素已完全渲染
await new Promise(resolve => {
requestAnimationFrame(() => {
requestAnimationFrame(resolve);
});
});
base64Image = svg2Base64(svgElement);
console.log(`SVG serialization result for ${el.id}:`, {
success: !!base64Image,
length: base64Image ? base64Image.length : 0,
preview: base64Image ? base64Image.substring(0, 100) + '...' : 'null'
});
if (base64Image && base64Image.length > 100) {
renderSuccess = true;
console.log(`SVG serialization successful for ${el.id}`);
}
}
} catch (svgError) {
console.warn(`SVG serialization failed for ${el.id}:`, svgError);
}
// 策略2: 如果SVG序列化失败,使用Canvas渲染
if (!renderSuccess) {
try {
console.log(`Attempting Canvas rendering for ${el.id}`);
// Canvas渲染选项
const renderOptions = {
scale: 2, // 高分辨率渲染
backgroundColor: null, // 透明背景
useCORS: true,
timeout: 15000, // 增加超时时间
format: 'png' as const,
quality: 0.95
};
base64Image = await renderElementToBase64(targetElement, renderOptions);
console.log(`Canvas rendering result for ${el.id}:`, {
success: !!base64Image,
length: base64Image ? base64Image.length : 0,
preview: base64Image ? base64Image.substring(0, 100) + '...' : 'null'
});
if (base64Image && base64Image.length > 100) {
renderSuccess = true;
console.log(`Canvas rendering successful for ${el.id}`);
}
} catch (canvasError) {
console.error(`Canvas rendering failed for ${el.id}:`, canvasError);
}
}
// 策略3: 如果前两种方法都失败,尝试简化的SVG渲染
if (!renderSuccess) {
try {
console.log(`Attempting simplified SVG rendering for ${el.id}`);
const svgElement = targetElement.tagName.toLowerCase() === 'svg'
? targetElement
: targetElement.querySelector('svg');
if (svgElement) {
// 创建简化的SVG副本
const simplifiedSVG = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const rect = svgElement.getBoundingClientRect();
simplifiedSVG.setAttribute('width', (rect.width || 100).toString());
simplifiedSVG.setAttribute('height', (rect.height || 100).toString());
simplifiedSVG.setAttribute('viewBox', `0 0 ${rect.width || 100} ${rect.height || 100}`);
simplifiedSVG.innerHTML = svgElement.innerHTML;
base64Image = svg2Base64(simplifiedSVG);
if (base64Image && base64Image.length > 100) {
renderSuccess = true;
console.log(`Simplified SVG rendering successful for ${el.id}`);
}
}
} catch (simplifiedError) {
console.error(`Simplified SVG rendering failed for ${el.id}:`, simplifiedError);
}
}
// 如果所有渲染策略都失败,使用路径导出作为最后备选
if (!renderSuccess) {
console.warn(`All rendering strategies failed for ${el.id}, falling back to path export`);
// 最终降级到路径导出
console.log(`Final fallback to path-based export for ${el.id}`);
const scale = {
x: el.width / el.viewBox[0],
y: el.height / el.viewBox[1],
};
const points = formatPoints(toPoints(el.path), scale);
let fillColor = formatColor(el.fill);
if (el.gradient) {
const colors = el.gradient.colors;
const color1 = colors[0].color;
const color2 = colors[colors.length - 1].color;
const color = tinycolor.mix(color1, color2).toHexString();
fillColor = formatColor(color);
}
if (el.pattern) fillColor = formatColor('#00000000');
const opacity = el.opacity === undefined ? 1 : el.opacity;
const fallbackOptions: pptxgen.ShapeProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
fill: { color: fillColor.color, transparency: (1 - fillColor.alpha * opacity) * 100 },
points,
};
if (el.flipH) fallbackOptions.flipH = el.flipH;
if (el.flipV) fallbackOptions.flipV = el.flipV;
if (el.shadow) fallbackOptions.shadow = getShadowOption(el.shadow);
if (el.outline?.width) fallbackOptions.line = getOutlineOption(el.outline);
if (el.rotate) fallbackOptions.rotate = el.rotate;
if (el.link) {
const linkOption = getLinkOption(el.link);
if (linkOption) fallbackOptions.hyperlink = linkOption;
}
pptxSlide.addShape('custGeom' as pptxgen.ShapeType, fallbackOptions);
continue;
}
// 添加渲染后的图像到幻灯片
const options: pptxgen.ImageProps = {
data: base64Image,
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
}
if (el.rotate) options.rotate = el.rotate
if (el.flipH) options.flipH = el.flipH
if (el.flipV) options.flipV = el.flipV
if (el.link) {
const linkOption = getLinkOption(el.link)
if (linkOption) options.hyperlink = linkOption
}
console.log(`Successfully added Canvas-rendered image for shape ${el.id}`);
pptxSlide.addImage(options)
}
else {
const scale = {
x: el.width / el.viewBox[0],
y: el.height / el.viewBox[1],
}
const points = formatPoints(toPoints(el.path), scale)
let fillColor = formatColor(el.fill)
if (el.gradient) {
const colors = el.gradient.colors
const color1 = colors[0].color
const color2 = colors[colors.length - 1].color
const color = tinycolor.mix(color1, color2).toHexString()
fillColor = formatColor(color)
}
if (el.pattern) fillColor = formatColor('#00000000')
const opacity = el.opacity === undefined ? 1 : el.opacity
const options: pptxgen.ShapeProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
fill: { color: fillColor.color, transparency: (1 - fillColor.alpha * opacity) * 100 },
points,
}
if (el.flipH) options.flipH = el.flipH
if (el.flipV) options.flipV = el.flipV
if (el.shadow) options.shadow = getShadowOption(el.shadow)
if (el.outline?.width) options.line = getOutlineOption(el.outline)
if (el.rotate) options.rotate = el.rotate
if (el.link) {
const linkOption = getLinkOption(el.link)
if (linkOption) options.hyperlink = linkOption
}
pptxSlide.addShape('custGeom' as pptxgen.ShapeType, options)
}
if (el.text) {
const textProps = formatHTML(el.text.content)
const options: pptxgen.TextPropsOptions = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
fontSize: defaultFontSize / ratioPx2Pt.value,
fontFace: '微软雅黑',
color: '#000000',
paraSpaceBefore: 5 / ratioPx2Pt.value,
valign: el.text.align,
}
if (el.rotate) options.rotate = el.rotate
if (el.text.defaultColor) options.color = formatColor(el.text.defaultColor).color
if (el.text.defaultFontName) options.fontFace = el.text.defaultFontName
pptxSlide.addText(textProps, options)
}
if (el.pattern) {
const options: pptxgen.ImageProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
}
if (isBase64Image(el.pattern)) options.data = el.pattern
else options.path = el.pattern
if (el.flipH) options.flipH = el.flipH
if (el.flipV) options.flipV = el.flipV
if (el.rotate) options.rotate = el.rotate
if (el.link) {
const linkOption = getLinkOption(el.link)
if (linkOption) options.hyperlink = linkOption
}
pptxSlide.addImage(options)
}
}
else if (el.type === 'line') {
const path = getLineElementPath(el)
const points = formatPoints(toPoints(path))
const { minX, maxX, minY, maxY } = getElementRange(el)
const c = formatColor(el.color)
const options: pptxgen.ShapeProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: (maxX - minX) / ratioPx2Inch.value,
h: (maxY - minY) / ratioPx2Inch.value,
line: {
color: c.color,
transparency: (1 - c.alpha) * 100,
width: el.width / ratioPx2Pt.value,
dashType: dashTypeMap[el.style] as 'solid' | 'dash' | 'sysDot',
beginArrowType: el.points[0] ? 'arrow' : 'none',
endArrowType: el.points[1] ? 'arrow' : 'none',
},
points,
}
if (el.shadow) options.shadow = getShadowOption(el.shadow)
pptxSlide.addShape('custGeom' as pptxgen.ShapeType, options)
}
else if (el.type === 'chart') {
const chartData = []
for (let i = 0; i < el.data.series.length; i++) {
const item = el.data.series[i]
chartData.push({
name: `系列${i + 1}`,
labels: el.data.labels,
values: item,
})
}
let chartColors: string[] = []
if (el.themeColors.length === 10) chartColors = el.themeColors.map(color => formatColor(color).color)
else if (el.themeColors.length === 1) chartColors = tinycolor(el.themeColors[0]).analogous(10).map(color => formatColor(color.toHexString()).color)
else {
const len = el.themeColors.length
const supplement = tinycolor(el.themeColors[len - 1]).analogous(10 + 1 - len).map(color => color.toHexString())
chartColors = [...el.themeColors.slice(0, len - 1), ...supplement].map(color => formatColor(color).color)
}
const options: pptxgen.IChartOpts = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
chartColors: (el.chartType === 'pie' || el.chartType === 'ring') ? chartColors : chartColors.slice(0, el.data.series.length),
}
const textColor = formatColor(el.textColor || '#000000').color
options.catAxisLabelColor = textColor
options.valAxisLabelColor = textColor
const fontSize = 14 / ratioPx2Pt.value
options.catAxisLabelFontSize = fontSize
options.valAxisLabelFontSize = fontSize
if (el.fill || el.outline) {
const plotArea: pptxgen.IChartPropsFillLine = {}
if (el.fill) {
plotArea.fill = { color: formatColor(el.fill).color }
}
if (el.outline) {
plotArea.border = {
pt: el.outline.width! / ratioPx2Pt.value,
color: formatColor(el.outline.color!).color,
}
}
options.plotArea = plotArea
}
if ((el.data.series.length > 1 && el.chartType !== 'scatter') || el.chartType === 'pie' || el.chartType === 'ring') {
options.showLegend = true
options.legendPos = 'b'
options.legendColor = textColor
options.legendFontSize = fontSize
}
let type = pptx.ChartType.bar
if (el.chartType === 'bar') {
type = pptx.ChartType.bar
options.barDir = 'col'
if (el.options?.stack) options.barGrouping = 'stacked'
}
else if (el.chartType === 'column') {
type = pptx.ChartType.bar
options.barDir = 'bar'
if (el.options?.stack) options.barGrouping = 'stacked'
}
else if (el.chartType === 'line') {
type = pptx.ChartType.line
if (el.options?.lineSmooth) options.lineSmooth = true
}
else if (el.chartType === 'area') {
type = pptx.ChartType.area
}
else if (el.chartType === 'radar') {
type = pptx.ChartType.radar
}
else if (el.chartType === 'scatter') {
type = pptx.ChartType.scatter
options.lineSize = 0
}
else if (el.chartType === 'pie') {
type = pptx.ChartType.pie
}
else if (el.chartType === 'ring') {
type = pptx.ChartType.doughnut
options.holeSize = 60
}
pptxSlide.addChart(type, chartData, options)
}
else if (el.type === 'table') {
const hiddenCells = []
for (let i = 0; i < el.data.length; i++) {
const rowData = el.data[i]
for (let j = 0; j < rowData.length; j++) {
const cell = rowData[j]
if (cell.colspan > 1 || cell.rowspan > 1) {
for (let row = i; row < i + cell.rowspan; row++) {
for (let col = row === i ? j + 1 : j; col < j + cell.colspan; col++) hiddenCells.push(`${row}_${col}`)
}
}
}
}
const tableData = []
const theme = el.theme
let themeColor: FormatColor | null = null
let subThemeColors: FormatColor[] = []
if (theme) {
themeColor = formatColor(theme.color)
subThemeColors = getTableSubThemeColor(theme.color).map(item => formatColor(item))
}
for (let i = 0; i < el.data.length; i++) {
const row = el.data[i]
const _row = []
for (let j = 0; j < row.length; j++) {
const cell = row[j]
const cellOptions: pptxgen.TableCellProps = {
colspan: cell.colspan,
rowspan: cell.rowspan,
bold: cell.style?.bold || false,
italic: cell.style?.em || false,
underline: { style: cell.style?.underline ? 'sng' : 'none' },
align: cell.style?.align || 'left',
valign: 'middle',
fontFace: cell.style?.fontname || '微软雅黑',
fontSize: (cell.style?.fontsize ? parseInt(cell.style?.fontsize) : 14) / ratioPx2Pt.value,
}
if (theme && themeColor) {
let c: FormatColor
if (i % 2 === 0) c = subThemeColors[1]
else c = subThemeColors[0]
if (theme.rowHeader && i === 0) c = themeColor
else if (theme.rowFooter && i === el.data.length - 1) c = themeColor
else if (theme.colHeader && j === 0) c = themeColor
else if (theme.colFooter && j === row.length - 1) c = themeColor
cellOptions.fill = { color: c.color, transparency: (1 - c.alpha) * 100 }
}
if (cell.style?.backcolor) {
const c = formatColor(cell.style.backcolor)
cellOptions.fill = { color: c.color, transparency: (1 - c.alpha) * 100 }
}
if (cell.style?.color) cellOptions.color = formatColor(cell.style.color).color
if (!hiddenCells.includes(`${i}_${j}`)) {
_row.push({
text: cell.text,
options: cellOptions,
})
}
}
if (_row.length) tableData.push(_row)
}
const options: pptxgen.TableProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
colW: el.colWidths.map(item => el.width * item / ratioPx2Inch.value),
}
if (el.theme) options.fill = { color: '#ffffff' }
if (el.outline.width && el.outline.color) {
options.border = {
type: el.outline.style === 'solid' ? 'solid' : 'dash',
pt: el.outline.width / ratioPx2Pt.value,
color: formatColor(el.outline.color).color,
}
}
pptxSlide.addTable(tableData, options)
}
else if (el.type === 'latex') {
const svgRef = document.querySelector(`.thumbnail-list .base-element-${el.id} svg`) as HTMLElement
const base64SVG = svg2Base64(svgRef)
const options: pptxgen.ImageProps = {
data: base64SVG,
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
}
if (el.link) {
const linkOption = getLinkOption(el.link)
if (linkOption) options.hyperlink = linkOption
}
pptxSlide.addImage(options)
}
else if (!ignoreMedia && (el.type === 'video' || el.type === 'audio')) {
const options: pptxgen.MediaProps = {
x: el.left / ratioPx2Inch.value,
y: el.top / ratioPx2Inch.value,
w: el.width / ratioPx2Inch.value,
h: el.height / ratioPx2Inch.value,
path: el.src,
type: el.type,
}
if (el.type === 'video' && el.poster) options.cover = el.poster
const extMatch = el.src.match(/\.([a-zA-Z0-9]+)(?:[\?#]|$)/)
if (extMatch && extMatch[1]) options.extn = extMatch[1]
else if (el.ext) options.extn = el.ext
const videoExts = ['avi', 'mp4', 'm4v', 'mov', 'wmv']
const audioExts = ['mp3', 'm4a', 'mp4', 'wav', 'wma']
if (options.extn && [...videoExts, ...audioExts].includes(options.extn)) {
pptxSlide.addMedia(options)
}
}
}
}
setTimeout(() => {
pptx.writeFile({ fileName: `${title.value}.pptx` }).then(() => exporting.value = false).catch(() => {
exporting.value = false
message.error('导出失败')
})
}, 200)
}
return {
exporting,
exportImage,
exportJSON,
exportSpecificFile,
exportHTML,
exportPPTX,
generateHTMLPresentation,
}
} |