useImport.ts 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486
  1. import { ref, nextTick } from 'vue'
  2. import { storeToRefs } from 'pinia'
  3. import { parse, type Shape, type Element, type ChartItem, type BaseElement } from 'pptxtojson'
  4. import { nanoid } from 'nanoid'
  5. import { useSlidesStore } from '@/store'
  6. import { lang } from '@/main'
  7. import { decrypt } from '@/utils/crypto'
  8. import { type ShapePoolItem, SHAPE_LIST, SHAPE_PATH_FORMULAS } from '@/configs/shapes'
  9. import useAddSlidesOrElements from '@/hooks/useAddSlidesOrElements'
  10. import useSlideHandler from '@/hooks/useSlideHandler'
  11. import useHistorySnapshot from './useHistorySnapshot'
  12. import message from '@/utils/message'
  13. import { getSvgPathRange } from '@/utils/svgPathParser'
  14. import { showConfirmDialog } from '@/utils/confirmDialog'
  15. import { EMFJS, WMFJS } from 'rtf.js'
  16. import * as UTIF from 'utif2'
  17. import type {
  18. Slide,
  19. TableCellStyle,
  20. TableCell,
  21. ChartType,
  22. SlideBackground,
  23. PPTShapeElement,
  24. PPTLineElement,
  25. PPTImageElement,
  26. ShapeTextAlign,
  27. PPTTextElement,
  28. PPTVideoElement,
  29. PPTAudioElement,
  30. ChartOptions,
  31. Gradient,
  32. } from '@/types/slides'
  33. const convertFontSizePtToPx = (html: string, ratio: number, autoFit: any) => {
  34. if (autoFit?.fontScale && autoFit?.type == 'text') {
  35. ratio = ratio * autoFit.fontScale / 100
  36. }
  37. // return html;
  38. return html.replace(/\s*([\d.]+)pt/g, (match, p1) => {
  39. return `${Math.round(parseFloat(p1) * ratio)}px `
  40. })
  41. }
  42. const getStyle = (htmlString: string) => {
  43. // return html;
  44. // 1. 创建 DOMParser 实例
  45. const parser = new DOMParser()
  46. // 2. 解析 HTML 字符串为文档对象
  47. const doc = parser.parseFromString(htmlString, 'text/html')
  48. // 3. 获取 p 元素
  49. const firstElem = doc.querySelector('p, ul, ol, table');
  50. // 读取该元素的 allstyle 属性
  51. const styleAttr = firstElem?.getAttribute('allstyle');
  52. console.log(styleAttr) // 输出完整的 style 字符串
  53. return styleAttr || ''
  54. }
  55. export default () => {
  56. const slidesStore = useSlidesStore()
  57. const { slides, theme, viewportRatio, title, viewportSize } = storeToRefs(useSlidesStore())
  58. const { addHistorySnapshot } = useHistorySnapshot()
  59. const { addSlidesFromData } = useAddSlidesOrElements()
  60. const { isEmptySlide } = useSlideHandler()
  61. const exporting = ref(false)
  62. const imgExporting = ref(false)
  63. // 导入JSON文件
  64. const importJSON = (files: FileList, cover = false) => {
  65. const file = files[0]
  66. const reader = new FileReader()
  67. reader.addEventListener('load', () => {
  68. try {
  69. const { slides } = JSON.parse(reader.result as string)
  70. if (cover) {
  71. slidesStore.updateSlideIndex(0)
  72. slidesStore.setSlides(slides)
  73. addHistorySnapshot()
  74. }
  75. else if (isEmptySlide.value) {
  76. slidesStore.setSlides(slides)
  77. addHistorySnapshot()
  78. }
  79. else addSlidesFromData(slides)
  80. }
  81. catch {
  82. message.error(lang.ssFileReadFail)
  83. }
  84. })
  85. reader.readAsText(file)
  86. }
  87. // 直接读取JSON功能,暴露到window.readJSON
  88. const readJSON = (jsonData: string | any, cover = false) => {
  89. try {
  90. console.log('readJSON 开始执行:', { jsonData, cover })
  91. let parsedData
  92. if (typeof jsonData === 'string') {
  93. parsedData = JSON.parse(jsonData)
  94. console.log('解析字符串后的数据:', parsedData)
  95. }
  96. else {
  97. parsedData = jsonData
  98. }
  99. // 提取所有可能的数据
  100. const slides = parsedData.slides || parsedData
  101. const title = parsedData.title
  102. const theme = parsedData.theme
  103. const width = parsedData.width
  104. const height = parsedData.height
  105. const viewportRatio = parsedData.viewportRatio || (height && width ? height / width : undefined)
  106. console.log('提取的数据:', { slides: slides.length, title, theme, width, height, viewportRatio })
  107. // 更新幻灯片数据
  108. if (cover) {
  109. console.log('覆盖模式:更新幻灯片数据')
  110. slidesStore.updateSlideIndex(0)
  111. slidesStore.setSlides(slides)
  112. addHistorySnapshot()
  113. }
  114. else if (isEmptySlide.value) {
  115. console.log('空幻灯片模式:更新幻灯片数据')
  116. slidesStore.setSlides(slides)
  117. addHistorySnapshot()
  118. }
  119. else {
  120. console.log('添加模式:添加幻灯片数据')
  121. addSlidesFromData(slides)
  122. }
  123. // 同步更新其他相关内容
  124. if (title !== undefined) {
  125. console.log('正在更新标题:', title)
  126. slidesStore.setTitle(title)
  127. console.log('标题更新完成')
  128. }
  129. if (theme !== undefined) {
  130. console.log('正在更新主题:', theme)
  131. slidesStore.setTheme(theme)
  132. console.log('主题更新完成')
  133. }
  134. // 更新视口尺寸(如果提供了的话)
  135. if (width !== undefined && height !== undefined) {
  136. console.log('正在触发视口尺寸更新事件:', { width, height, viewportRatio })
  137. // 同时也要更新slidesStore中的相关数据
  138. if (slidesStore.setViewportSize) {
  139. console.log('正在更新store中的视口尺寸')
  140. slidesStore.setViewportSize(width)
  141. if (slidesStore.setViewportRatio && viewportRatio !== undefined) {
  142. slidesStore.setViewportRatio(viewportRatio)
  143. console.log('视口比例已更新:', viewportRatio)
  144. }
  145. }
  146. window.dispatchEvent(new CustomEvent('viewportSizeUpdated', {
  147. detail: { width, height, viewportRatio }
  148. }))
  149. console.log('视口尺寸更新事件已触发')
  150. }
  151. // 导入成功后,触发画布尺寸更新
  152. // 使用 nextTick 确保DOM更新完成后再触发
  153. console.log('开始触发画布尺寸更新事件...')
  154. nextTick(() => {
  155. console.log('DOM更新完成,触发 slidesDataUpdated 事件')
  156. // 触发自定义事件,通知需要更新画布尺寸的组件
  157. window.dispatchEvent(new CustomEvent('slidesDataUpdated', {
  158. detail: {
  159. slides,
  160. cover,
  161. title,
  162. theme,
  163. width,
  164. height,
  165. viewportRatio,
  166. timestamp: Date.now()
  167. }
  168. }))
  169. console.log('slidesDataUpdated 事件已触发')
  170. // 检查并调整幻灯片索引,确保在有效范围内
  171. const newSlideCount = slides.length
  172. const currentIndex = slidesStore.slideIndex
  173. if (currentIndex >= newSlideCount) {
  174. console.log('调整幻灯片索引:', currentIndex, '->', Math.max(0, newSlideCount - 1))
  175. slidesStore.updateSlideIndex(Math.max(0, newSlideCount - 1))
  176. }
  177. console.log('画布尺寸更新事件处理完成')
  178. })
  179. console.log('readJSON 执行成功')
  180. return { success: true, slides, title, theme, width, height, viewportRatio }
  181. }
  182. catch (error) {
  183. console.error('readJSON 执行失败:', error)
  184. const errorMsg = lang.ssJsonReadFail
  185. message.error(errorMsg)
  186. return { success: false, error: errorMsg, details: error }
  187. }
  188. }
  189. // 导出JSON文件
  190. const exportJSON2 = () => {
  191. const json = {
  192. title: title.value,
  193. width: viewportSize.value,
  194. height: viewportSize.value * viewportRatio.value,
  195. theme: theme.value,
  196. slides: slides.value,
  197. }
  198. return json
  199. }
  200. // 优化暴露到 window 对象的方式,避免重复赋值
  201. if (typeof window !== 'undefined') {
  202. const win = window as any
  203. if (!win.exportJSON) win.exportJSON = exportJSON2
  204. if (!win.readJSON) win.readJSON = readJSON
  205. if (!win.imgExporting) win.imgExporting = () => imgExporting.value
  206. }
  207. // 导入pptist文件
  208. const importSpecificFile = (files: FileList, cover = false) => {
  209. const file = files[0]
  210. const reader = new FileReader()
  211. reader.addEventListener('load', () => {
  212. try {
  213. const { slides } = JSON.parse(decrypt(reader.result as string))
  214. if (cover) {
  215. slidesStore.updateSlideIndex(0)
  216. slidesStore.setSlides(slides)
  217. addHistorySnapshot()
  218. }
  219. else if (isEmptySlide.value) {
  220. slidesStore.setSlides(slides)
  221. addHistorySnapshot()
  222. }
  223. else addSlidesFromData(slides)
  224. }
  225. catch {
  226. message.error(lang.ssFileReadFail)
  227. }
  228. })
  229. reader.readAsText(file)
  230. }
  231. const rotateLine = (line: PPTLineElement, angleDeg: number) => {
  232. const { start, end } = line
  233. const angleRad = angleDeg * Math.PI / 180
  234. const midX = (start[0] + end[0]) / 2
  235. const midY = (start[1] + end[1]) / 2
  236. const startTransX = start[0] - midX
  237. const startTransY = start[1] - midY
  238. const endTransX = end[0] - midX
  239. const endTransY = end[1] - midY
  240. const cosA = Math.cos(angleRad)
  241. const sinA = Math.sin(angleRad)
  242. const startRotX = startTransX * cosA - startTransY * sinA
  243. const startRotY = startTransX * sinA + startTransY * cosA
  244. const endRotX = endTransX * cosA - endTransY * sinA
  245. const endRotY = endTransX * sinA + endTransY * cosA
  246. const startNewX = startRotX + midX
  247. const startNewY = startRotY + midY
  248. const endNewX = endRotX + midX
  249. const endNewY = endRotY + midY
  250. const beforeMinX = Math.min(start[0], end[0])
  251. const beforeMinY = Math.min(start[1], end[1])
  252. const afterMinX = Math.min(startNewX, endNewX)
  253. const afterMinY = Math.min(startNewY, endNewY)
  254. const startAdjustedX = startNewX - afterMinX
  255. const startAdjustedY = startNewY - afterMinY
  256. const endAdjustedX = endNewX - afterMinX
  257. const endAdjustedY = endNewY - afterMinY
  258. const startAdjusted: [number, number] = [startAdjustedX, startAdjustedY]
  259. const endAdjusted: [number, number] = [endAdjustedX, endAdjustedY]
  260. const offset = [afterMinX - beforeMinX, afterMinY - beforeMinY]
  261. return {
  262. start: startAdjusted,
  263. end: endAdjusted,
  264. offset,
  265. }
  266. }
  267. const parseLineElement = (el: Shape, ratio: number) => {
  268. let start: [number, number] = [0, 0]
  269. let end: [number, number] = [0, 0]
  270. if (!el.isFlipV && !el.isFlipH) { // 右下
  271. start = [0, 0]
  272. end = [el.width, el.height]
  273. }
  274. else if (el.isFlipV && el.isFlipH) { // 左上
  275. start = [el.width, el.height]
  276. end = [0, 0]
  277. }
  278. else if (el.isFlipV && !el.isFlipH) { // 右上
  279. start = [0, el.height]
  280. end = [el.width, 0]
  281. }
  282. else { // 左下
  283. start = [el.width, 0]
  284. end = [0, el.height]
  285. }
  286. const data: PPTLineElement = {
  287. type: 'line',
  288. id: nanoid(10),
  289. width: +((el.borderWidth || 1) * ratio).toFixed(2),
  290. left: el.left,
  291. top: el.top,
  292. start,
  293. end,
  294. style: el.borderType,
  295. color: el.borderColor,
  296. points: ['', /straightConnector/.test(el.shapType) ? 'arrow' : '']
  297. }
  298. if (el.rotate) {
  299. const { start, end, offset } = rotateLine(data, el.rotate)
  300. data.start = start
  301. data.end = end
  302. data.left = data.left + offset[0]
  303. data.top = data.top + offset[1]
  304. }
  305. if (/bentConnector/.test(el.shapType)) {
  306. data.broken2 = [
  307. Math.abs(data.start[0] - data.end[0]) / 2,
  308. Math.abs(data.start[1] - data.end[1]) / 2,
  309. ]
  310. }
  311. if (/curvedConnector/.test(el.shapType)) {
  312. const cubic: [number, number] = [
  313. Math.abs(data.start[0] - data.end[0]) / 2,
  314. Math.abs(data.start[1] - data.end[1]) / 2,
  315. ]
  316. data.cubic = [cubic, cubic]
  317. }
  318. return data
  319. }
  320. const flipGroupElements = (elements: BaseElement[], axis: 'x' | 'y') => {
  321. const minX = Math.min(...elements.map(el => el.left))
  322. const maxX = Math.max(...elements.map(el => el.left + el.width))
  323. const minY = Math.min(...elements.map(el => el.top))
  324. const maxY = Math.max(...elements.map(el => el.top + el.height))
  325. const centerX = (minX + maxX) / 2
  326. const centerY = (minY + maxY) / 2
  327. return elements.map(element => {
  328. const newElement = { ...element }
  329. if (axis === 'y') newElement.left = 2 * centerX - element.left - element.width
  330. if (axis === 'x') newElement.top = 2 * centerY - element.top - element.height
  331. return newElement
  332. })
  333. }
  334. const calculateRotatedPosition = (
  335. x: number,
  336. y: number,
  337. w: number,
  338. h: number,
  339. ox: number,
  340. oy: number,
  341. k: number,
  342. ) => {
  343. const radians = k * (Math.PI / 180)
  344. const containerCenterX = x + w / 2
  345. const containerCenterY = y + h / 2
  346. const relativeX = ox - w / 2
  347. const relativeY = oy - h / 2
  348. const rotatedX = relativeX * Math.cos(radians) + relativeY * Math.sin(radians)
  349. const rotatedY = -relativeX * Math.sin(radians) + relativeY * Math.cos(radians)
  350. const graphicX = containerCenterX + rotatedX
  351. const graphicY = containerCenterY + rotatedY
  352. return { x: graphicX, y: graphicY }
  353. }
  354. /**
  355. * 将 base64 字符串或 Blob 转换为 File 对象
  356. */
  357. const dataToFile = async (data: string | Blob, filename: string, videoMimeType: string): File => {
  358. if (typeof data === 'string') {
  359. // 1. 通过 fetch 获取 Blob 数据
  360. const response = await fetch(data)
  361. if (!response.ok) {
  362. throw new Error(`Failed to fetch blob: ${response.statusText}`)
  363. }
  364. const blob = await response.blob()
  365. // 2. 将 Blob 转换为 File 对象
  366. // 如果原 Blob 有 type,会自动保留;否则可手动指定 videoMimeType
  367. const file = new File([blob], filename, { type: videoMimeType || blob.type })
  368. return file
  369. }
  370. else if (data instanceof Blob) {
  371. return new File([data], filename, { type: data.type })
  372. }
  373. throw new Error('Unsupported data type')
  374. }
  375. /*
  376. // 你原有的 dataToFile 函数保持不变
  377. const dataToFile = async (data: string | Blob, filename: string, videoMimeType: string): Promise<File> => {
  378. if (typeof data === 'string') {
  379. const response = await fetch(data);
  380. if (!response.ok) {
  381. throw new Error(`Failed to fetch blob: ${response.statusText}`);
  382. }
  383. const blob = await response.blob();
  384. const mime = videoMimeType || blob.type;
  385. return new File([blob], filename, { type: mime });
  386. } else if (data instanceof Blob) {
  387. return new File([data], filename, { type: data.type });
  388. }
  389. throw new Error('Unsupported data type');
  390. };
  391. const convertVideoToMP4 = async (
  392. videoSource: string | Blob,
  393. outputFilename: string = `video_${Date.now()}.mp4`
  394. ): Promise<File> => {
  395. // 1. 检查浏览器支持
  396. const supported = await canEncode();
  397. if (!supported) {
  398. throw new Error('当前浏览器不支持 WebCodecs,请使用最新 Chrome/Edge 并确保 HTTPS');
  399. }
  400. // 2. 转为 File
  401. const inputFile = await dataToFile(videoSource, 'input.mp4', 'video/mp4');
  402. // 3. 创建 VideoFile 对象(webcodecs-encoder 的输入包装)
  403. //const videoFile = new VideoFile(inputFile);
  404. const videoFile = {
  405. file: inputFile,
  406. type: 'video/mp4'
  407. };
  408. // 4. 执行编码
  409. const encodedData = await encode(videoFile, {
  410. quality: 'high',
  411. video: {
  412. codec: 'av1',
  413. bitrate: 2_000_000,
  414. hardwareAcceleration: 'prefer-hardware'
  415. },
  416. audio: false, // 显式禁用音频编码
  417. container: 'mp4',
  418. onProgress: (progress) => console.log(progress)
  419. });
  420. // 5. 返回 File
  421. return new File([encodedData], outputFilename, { type: 'video/mp4' });
  422. };
  423. */
  424. /*
  425. const makeWhiteTransparent = async (
  426. data: string | Blob,
  427. filename: string,
  428. options?: { tolerance?: number }
  429. ): Promise<File> => {
  430. const tolerance = options?.tolerance ?? 30 // 容差值,控制哪些颜色被视为白色
  431. const distThreshold = options?.tolerance ?? 50;
  432. // 1. 将输入数据统一为 Blob 或可直接用于加载的 URL
  433. let imageUrl: string
  434. let blob: Blob
  435. if (typeof data === 'string') {
  436. // 如果是 Base64,直接用作 src(data URL)
  437. imageUrl = data.startsWith('data:') ? data : `data:image/png;base64,${data}`
  438. }
  439. else if (data instanceof Blob) {
  440. // 如果是 Blob,创建对象 URL
  441. imageUrl = URL.createObjectURL(data)
  442. blob = data // 暂存,后续释放 URL 用
  443. }
  444. else {
  445. throw new Error('Unsupported data type')
  446. }
  447. // 2. 加载图像到 Image 元素
  448. const img = await new Promise<HTMLImageElement>((resolve, reject) => {
  449. const image = new Image()
  450. image.onload = () => resolve(image)
  451. image.onerror = reject
  452. image.src = imageUrl
  453. // 如果图像来自跨域,可能需要设置 crossOrigin
  454. // image.crossOrigin = 'anonymous';
  455. })
  456. // 3. 创建 Canvas 并绘制图像
  457. const canvas = document.createElement('canvas')
  458. canvas.width = img.width
  459. canvas.height = img.height
  460. const ctx = canvas.getContext('2d')!
  461. ctx.drawImage(img, 0, 0)
  462. // 4. 获取像素数据并处理
  463. const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
  464. const dataArray = imageData.data
  465. for (let i = 0; i < dataArray.length; i += 4) {
  466. const r = dataArray[i]
  467. const g = dataArray[i + 1]
  468. const b = dataArray[i + 2]
  469. // 判断颜色是否接近白色(RGB 都大于 255 - tolerance)
  470. if (r > 255 - tolerance && g > 255 - tolerance && b > 255 - tolerance) {
  471. dataArray[i + 3] = 0 // 设置 Alpha 为 0(完全透明)
  472. }
  473. }
  474. // 5. 将修改后的像素放回 Canvas
  475. ctx.putImageData(imageData, 0, 0)
  476. // 6. 将 Canvas 转换为 PNG Blob
  477. const outputBlob = await new Promise<Blob>((resolve) =>
  478. canvas.toBlob((blob) => resolve(blob!), 'image/png')
  479. )
  480. // 7. 清理对象 URL(如果之前创建过)
  481. if (typeof data !== 'string') {
  482. URL.revokeObjectURL(imageUrl)
  483. }
  484. // 8. 返回 File 对象
  485. return new File([outputBlob], filename, { type: 'image/png' })
  486. }
  487. */
  488. /**
  489. * 将图片中的白色背景变为透明
  490. * @param data 图片数据(Base64字符串 或 Blob)
  491. * @param filename 输出文件名
  492. * @param options 可选配置
  493. * @param options.tolerance 颜色距离容差(默认50,值越大越多的浅色被变透明)
  494. * @param options.removeMatte 是否去除白色边缘(默认true,可改善白边)
  495. * @returns 处理后的 PNG 格式 File 对象
  496. */
  497. /*
  498. const makeWhiteTransparent = async (
  499. data: string | Blob,
  500. filename: string,
  501. options?: { tolerance?: number }
  502. ): Promise<File> => {
  503. const tolerance = options?.tolerance ?? 15;
  504. // ----- 辅助函数:将输入统一转换为 { blob, mime } -----
  505. async function getBlobAndMime(input: string | Blob): Promise<{ blob: Blob; mime: string }> {
  506. if (input instanceof Blob) {
  507. return { blob: input, mime: input.type };
  508. }
  509. if (input.startsWith('data:')) {
  510. const response = await fetch(input);
  511. const blob = await response.blob();
  512. return { blob, mime: blob.type };
  513. }
  514. // 纯 base64 字符串,默认当作 PNG
  515. const binary = atob(input);
  516. const bytes = new Uint8Array(binary.length);
  517. for (let i = 0; i < binary.length; i++) {
  518. bytes[i] = binary.charCodeAt(i);
  519. }
  520. const blob = new Blob([bytes], { type: 'image/png' });
  521. return { blob, mime: 'image/png' };
  522. }
  523. // ----- 辅助函数:通过 MIME 或文件扩展名判断格式 -----
  524. function getFormat(mime: string, filename: string): string {
  525. const ext = filename.split('.').pop()?.toLowerCase();
  526. if (mime.startsWith('image/')) {
  527. const sub = mime.split('/')[1];
  528. if (sub === 'vnd.microsoft.icon') return 'ico';
  529. if (sub === 'x-emf' || sub === 'x-msmetafile') return 'emf';
  530. if (sub === 'tiff' || sub === 'x-tiff') return 'tiff';
  531. return sub;
  532. }
  533. // 兜底扩展名判断
  534. if (ext === 'emf' || ext === 'wmf') return 'emf';
  535. if (ext === 'tif' || ext === 'tiff') return 'tiff';
  536. return 'unknown';
  537. }
  538. // ----- 格式转换器 -----
  539. // 1. 浏览器原生支持的格式:通过 Image + Canvas 转为 PNG
  540. async function convertBrowserImageToPng(blob: Blob): Promise<Blob> {
  541. const url = URL.createObjectURL(blob);
  542. try {
  543. const img = await new Promise<HTMLImageElement>((resolve, reject) => {
  544. const image = new Image();
  545. image.onload = () => resolve(image);
  546. image.onerror = reject;
  547. image.src = url;
  548. });
  549. const canvas = document.createElement('canvas');
  550. canvas.width = img.width;
  551. canvas.height = img.height;
  552. const ctx = canvas.getContext('2d')!;
  553. ctx.drawImage(img, 0, 0);
  554. return await new Promise((resolve, reject) => {
  555. canvas.toBlob(blob => (blob ? resolve(blob) : reject(new Error('Canvas toBlob failed'))), 'image/png');
  556. });
  557. } finally {
  558. URL.revokeObjectURL(url);
  559. }
  560. }
  561. // 2. EMF/WMF 转 PNG(需要 wmf2png 库)
  562. async function convertEmfToPng(blob: Blob): Promise<Blob> {
  563. const arrayBuffer = await blob.arrayBuffer();
  564. const pngBuffer = await wmf2png(arrayBuffer);
  565. return new Blob([pngBuffer], { type: 'image/png' });
  566. }
  567. // 3. TIFF 转 PNG(需要 UTIF.js 库)
  568. async function convertTiffToPng(blob: Blob): Promise<Blob> {
  569. const arrayBuffer = await blob.arrayBuffer();
  570. const ifds = UTIF.decode(arrayBuffer);
  571. if (!ifds || ifds.length === 0) throw new Error('No TIFF image found');
  572. const rgba = UTIF.toRGBA8(ifds[0]);
  573. const canvas = document.createElement('canvas');
  574. canvas.width = ifds[0].width;
  575. canvas.height = ifds[0].height;
  576. const ctx = canvas.getContext('2d')!;
  577. const imageData = new ImageData(rgba, ifds[0].width, ifds[0].height);
  578. ctx.putImageData(imageData, 0, 0);
  579. return await new Promise((resolve, reject) => {
  580. canvas.toBlob(blob => (blob ? resolve(blob) : reject(new Error('TIFF to PNG failed'))), 'image/png');
  581. });
  582. }
  583. // ----- 主逻辑:获取原始 blob 和格式 -----
  584. let { blob, mime } = await getBlobAndMime(data);
  585. let format = getFormat(mime, filename);
  586. // 统一转为 PNG(除已经是 PNG 的以外,其它都转换)
  587. let pngBlob: Blob;
  588. if (format === 'png') {
  589. pngBlob = blob; // 直接复用,稍后做白色透明
  590. } else {
  591. // 根据格式选择转换器
  592. if (format === 'emf' || format === 'wmf') {
  593. pngBlob = await convertEmfToPng(blob);
  594. } else if (format === 'tiff' || format === 'x-tiff') {
  595. pngBlob = await convertTiffToPng(blob);
  596. } else {
  597. // 其它所有格式(jpeg, bmp, gif, webp, ico 等)都尝试用浏览器原生方法转换
  598. pngBlob = await convertBrowserImageToPng(blob);
  599. }
  600. // 更新文件名后缀为 .png
  601. filename = filename.replace(/\.[^.]*$/, '') + '.png';
  602. }
  603. // ----- 白色变透明处理(仅对 PNG 执行)-----
  604. const imageUrl = URL.createObjectURL(pngBlob);
  605. try {
  606. const img = await new Promise<HTMLImageElement>((resolve, reject) => {
  607. const image = new Image();
  608. image.onload = () => resolve(image);
  609. image.onerror = reject;
  610. image.src = imageUrl;
  611. });
  612. const canvas = document.createElement('canvas');
  613. canvas.width = img.width;
  614. canvas.height = img.height;
  615. const ctx = canvas.getContext('2d')!;
  616. ctx.drawImage(img, 0, 0);
  617. const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  618. const dataArray = imageData.data;
  619. for (let i = 0; i < dataArray.length; i += 4) {
  620. const r = dataArray[i];
  621. const g = dataArray[i + 1];
  622. const b = dataArray[i + 2];
  623. const dr = r - 255;
  624. const dg = g - 255;
  625. const db = b - 255;
  626. const dist = Math.sqrt(dr * dr + dg * dg + db * db);
  627. if (dist <= tolerance) {
  628. dataArray[i + 3] = 0;
  629. }
  630. }
  631. ctx.putImageData(imageData, 0, 0);
  632. const outputBlob = await new Promise<Blob>((resolve, reject) => {
  633. canvas.toBlob(blob => (blob ? resolve(blob) : reject(new Error('Canvas toBlob failed'))), 'image/png');
  634. });
  635. return new File([outputBlob], filename, { type: 'image/png' });
  636. } finally {
  637. URL.revokeObjectURL(imageUrl);
  638. }
  639. };
  640. */
  641. /**
  642. * 将图片统一处理:
  643. * - 对于浏览器原生支持的格式(JPEG, BMP, GIF, WebP 等):直接返回原始文件
  644. * - 对于 PNG:执行白色变透明处理后返回
  645. * - 对于 TIFF / EMF / WMF:先转换为 PNG,再执行白色变透明处理后返回
  646. */
  647. const makeWhiteTransparent = async (
  648. data: string | Blob,
  649. filename: string,
  650. options?: { tolerance?: number }
  651. ): Promise<File> => {
  652. const tolerance = options?.tolerance ?? 15
  653. // 1. 统一输入为 Blob 和 MIME
  654. const { blob, mime } = await getBlobAndMime(data)
  655. const format = getFormat(mime, filename)
  656. // 2. 浏览器原生支持的格式直接返回
  657. if (format === 'browser') {
  658. return new File([blob], filename, { type: mime })
  659. }
  660. // 3. 需要转换成 PNG 的格式
  661. let pngBlob: Blob
  662. if (format === 'tiff') {
  663. pngBlob = await convertTiffToPng(blob)
  664. }
  665. else if (format === 'emf') {
  666. pngBlob = await convertEmfToPng(blob)
  667. }
  668. else if (format === 'wmf') {
  669. pngBlob = await convertWmfToPng(blob)
  670. }
  671. else {
  672. // format === 'png' 的情况
  673. pngBlob = blob
  674. }
  675. // --- 新增:检测 PNG 是否已经包含透明背景 ---
  676. let alreadyTransparent = false
  677. // 无论原始格式是 PNG 还是转换后得到的 PNG,都进行检测
  678. const checkUrl = URL.createObjectURL(pngBlob)
  679. try {
  680. const img = await new Promise<HTMLImageElement>((resolve, reject) => {
  681. const image = new Image()
  682. image.onload = () => resolve(image)
  683. image.onerror = reject
  684. image.src = checkUrl
  685. })
  686. const canvas = document.createElement('canvas')
  687. canvas.width = img.width
  688. canvas.height = img.height
  689. const ctx = canvas.getContext('2d')!
  690. ctx.drawImage(img, 0, 0)
  691. alreadyTransparent = hasTransparency(img, ctx)
  692. }
  693. finally {
  694. URL.revokeObjectURL(checkUrl)
  695. }
  696. let transparentPngBlob: Blob
  697. transparentPngBlob = pngBlob
  698. /*
  699. if (alreadyTransparent) {
  700. // 图片已有透明背景,直接使用原 PNG Blob
  701. console.log('检测到透明背景,跳过白色变透明处理')
  702. transparentPngBlob = pngBlob
  703. }
  704. else {
  705. // 否则执行白色变透明处理
  706. transparentPngBlob = await makeWhiteTransparentFromPng(pngBlob, tolerance)
  707. }
  708. */
  709. const finalFilename = format === 'png' ? filename : filename.replace(/\.[^.]*$/, '') + '.png'
  710. return new File([transparentPngBlob], finalFilename, { type: 'image/png' })
  711. }
  712. // ================== 辅助函数 ==================
  713. async function getBlobAndMime(input: string | Blob): Promise<{ blob: Blob; mime: string }> {
  714. if (input instanceof Blob) return { blob: input, mime: input.type }
  715. if (input.startsWith('data:') || input.startsWith('blob:')) {
  716. const res = await fetch(input)
  717. const blob = await res.blob()
  718. return { blob, mime: blob.type }
  719. }
  720. const binary = atob(input)
  721. const bytes = new Uint8Array(binary.length)
  722. for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
  723. const blob = new Blob([bytes], { type: 'image/png' })
  724. return { blob, mime: 'image/png' }
  725. }
  726. function getFormat(mime: string, filename: string): string {
  727. const ext = filename.split('.').pop()?.toLowerCase()
  728. if (mime === 'image/png') return 'png'
  729. if (mime === 'image/tiff' || mime === 'image/x-tiff' || ext === 'tiff' || ext === 'tif') return 'tiff'
  730. if (mime === 'image/x-emf' || mime === 'application/x-emf' || ext === 'emf') return 'emf'
  731. if (mime === 'image/x-wmf' || mime === 'application/x-wmf' || ext === 'wmf') return 'wmf'
  732. return 'browser'
  733. }
  734. // TIFF 转 PNG(使用 UTIF.js)
  735. async function convertTiffToPng(blob: Blob): Promise<Blob> {
  736. const arrayBuffer = await blob.arrayBuffer()
  737. const ifds = UTIF.decode(arrayBuffer)
  738. if (!ifds || ifds.length === 0) throw new Error('No TIFF image found')
  739. UTIF.decodeImage(arrayBuffer, ifds[0])
  740. const rgba = UTIF.toRGBA8(ifds[0])
  741. const canvas = document.createElement('canvas')
  742. canvas.width = ifds[0].width
  743. canvas.height = ifds[0].height
  744. const ctx = canvas.getContext('2d')!
  745. ctx.putImageData(new ImageData(rgba, ifds[0].width, ifds[0].height), 0, 0)
  746. return new Promise((resolve, reject) => {
  747. canvas.toBlob(blob => (blob ? resolve(blob) : reject(new Error('TIFF to PNG failed'))), 'image/png')
  748. })
  749. }
  750. // 通用函数:将 EMF/WMF 通过 Renderer 转换为 PNG
  751. // 参考示例:https://github.com/wood/rtf.js/blob/master/demo/WMFJS.html
  752. async function convertMetafileToPng(
  753. arrayBuffer: ArrayBuffer,
  754. RendererClass: any
  755. ): Promise<Blob> {
  756. // 1. 创建 Renderer 实例
  757. const renderer = new RendererClass(arrayBuffer)
  758. // 2. 获取真实尺寸(保持原逻辑)
  759. let width = 800, height = 600
  760. try {
  761. const tempSettings = {
  762. width: '100%',
  763. height: '100%',
  764. xExt: 1000,
  765. yExt: 1000,
  766. mapMode: 8,
  767. }
  768. const tempSvg = renderer.render(tempSettings)
  769. const viewBox = tempSvg.getAttribute('viewBox')
  770. if (viewBox) {
  771. const parts = viewBox.split(/[\s,]+/)
  772. if (parts.length >= 4) {
  773. width = parseFloat(parts[2])
  774. height = parseFloat(parts[3])
  775. }
  776. } else {
  777. const svgWidth = tempSvg.getAttribute('width')
  778. const svgHeight = tempSvg.getAttribute('height')
  779. if (svgWidth && svgHeight) {
  780. width = parseFloat(svgWidth)
  781. height = parseFloat(svgHeight)
  782. }
  783. }
  784. } catch (e) {
  785. console.warn('Failed to get dimensions from SVG, using default', e)
  786. }
  787. // 3. 使用实际尺寸渲染最终 SVG
  788. const settings = {
  789. width: width + 'px',
  790. height: height + 'px',
  791. xExt: width,
  792. yExt: height,
  793. mapMode: 8,
  794. }
  795. const svg = renderer.render(settings)
  796. // 4. 序列化并修补 SVG 字符串
  797. const serializer = new XMLSerializer()
  798. let svgString = serializer.serializeToString(svg)
  799. // ✅ 关键修复:强制设置根元素宽高与 viewBox 一致
  800. const parser = new DOMParser()
  801. const svgDoc = parser.parseFromString(svgString, 'image/svg+xml')
  802. const svgRoot = svgDoc.documentElement
  803. // 确保有命名空间
  804. if (!svgRoot.hasAttribute('xmlns')) {
  805. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
  806. }
  807. // 强制设置宽高为确定的像素值(与 viewBox 的宽高一致)
  808. svgRoot.setAttribute('width', width.toString())
  809. svgRoot.setAttribute('height', height.toString())
  810. // 若原本没有 viewBox,根据获取的宽高补上
  811. if (!svgRoot.hasAttribute('viewBox')) {
  812. svgRoot.setAttribute('viewBox', `0 0 ${width} ${height}`)
  813. }
  814. svgString = new XMLSerializer().serializeToString(svgRoot)
  815. // 5. 后续 Image 加载与 canvas 绘制保持不变
  816. const blob = new Blob([svgString], { type: 'image/svg+xml' })
  817. const url = URL.createObjectURL(blob)
  818. try {
  819. const img = await new Promise<HTMLImageElement>((resolve, reject) => {
  820. const image = new Image()
  821. image.onload = () => resolve(image)
  822. image.onerror = reject
  823. image.src = url
  824. })
  825. const canvas = document.createElement('canvas')
  826. canvas.width = img.width
  827. canvas.height = img.height
  828. const ctx = canvas.getContext('2d')!
  829. ctx.drawImage(img, 0, 0)
  830. return new Promise((resolve, reject) => {
  831. canvas.toBlob(
  832. (blob) => (blob ? resolve(blob) : reject(new Error('Metafile to PNG failed'))),
  833. 'image/png'
  834. )
  835. })
  836. } finally {
  837. URL.revokeObjectURL(url)
  838. }
  839. }
  840. // EMF 转 PNG(使用 EMFJS.Renderer)
  841. async function convertEmfToPng(blob: Blob): Promise<Blob> {
  842. const arrayBuffer = await blob.arrayBuffer()
  843. return convertMetafileToPng(arrayBuffer, EMFJS.Renderer)
  844. }
  845. // WMF 转 PNG(使用 WMFJS.Renderer)
  846. async function convertWmfToPng(blob: Blob): Promise<Blob> {
  847. const arrayBuffer = await blob.arrayBuffer()
  848. return convertMetafileToPng(arrayBuffer, WMFJS.Renderer)
  849. }
  850. function hasTransparency(img: HTMLImageElement, ctx: CanvasRenderingContext2D): boolean {
  851. const imageData = ctx.getImageData(0, 0, img.width, img.height)
  852. const data = imageData.data
  853. // 遍历 Alpha 通道(索引 3)
  854. for (let i = 3; i < data.length; i += 4) {
  855. if (data[i] < 255) {
  856. return true // 发现任意一个像素不是完全不透明
  857. }
  858. }
  859. return false
  860. }
  861. // 对 PNG 执行白色变透明
  862. async function makeWhiteTransparentFromPng(pngBlob: Blob, tolerance: number): Promise<Blob> {
  863. const url = URL.createObjectURL(pngBlob)
  864. try {
  865. const img = await new Promise<HTMLImageElement>((resolve, reject) => {
  866. const image = new Image()
  867. image.onload = () => resolve(image)
  868. image.onerror = reject
  869. image.src = url
  870. })
  871. const canvas = document.createElement('canvas')
  872. canvas.width = img.width
  873. canvas.height = img.height
  874. const ctx = canvas.getContext('2d')!
  875. ctx.drawImage(img, 0, 0)
  876. const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
  877. const data = imageData.data
  878. for (let i = 0; i < data.length; i += 4) {
  879. const r = data[i]
  880. const g = data[i + 1]
  881. const b = data[i + 2]
  882. const dr = r - 255
  883. const dg = g - 255
  884. const db = b - 255
  885. if (Math.sqrt(dr * dr + dg * dg + db * db) <= tolerance) {
  886. data[i + 3] = 0
  887. }
  888. }
  889. ctx.putImageData(imageData, 0, 0)
  890. return new Promise((resolve, reject) => {
  891. canvas.toBlob(blob => (blob ? resolve(blob) : reject(new Error('Canvas toBlob failed'))), 'image/png')
  892. })
  893. }
  894. finally {
  895. URL.revokeObjectURL(url)
  896. }
  897. }
  898. /**
  899. * 上传 File 到 S3,返回公开访问的 URL
  900. */
  901. const uploadFileToS3 = (file: File): Promise<string> => {
  902. return new Promise((resolve, reject) => {
  903. if (typeof window === 'undefined' || !window.AWS) {
  904. reject(new Error('AWS SDK not available'))
  905. return
  906. }
  907. const credentials = {
  908. accessKeyId: 'AKIATLPEDU37QV5CHLMH',
  909. secretAccessKey: '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',
  910. }
  911. window.AWS.config.update(credentials)
  912. window.AWS.config.region = 'cn-northwest-1'
  913. const bucket = new window.AWS.S3({
  914. params: { Bucket: 'ccrb' }, httpOptions: {
  915. timeout: 600000 // 10分钟超时
  916. }
  917. })
  918. const ext = file.name.split('.').pop() || 'bin'
  919. const key = `${file.name.split('.')[0]}_${Date.now()}.${ext}`
  920. const params = {
  921. Key: 'pptto/' + key,
  922. ContentType: file.type,
  923. Body: file,
  924. ACL: 'public-read',
  925. }
  926. const options = {
  927. partSize: 5 * 1024 * 1024, // 2GB 分片,可酌情调小
  928. queueSize: 2,
  929. leavePartsOnError: true,
  930. }
  931. bucket
  932. .upload(params, options)
  933. .promise()
  934. .then(data => resolve(data.Location))
  935. .catch(err => reject(err))
  936. })
  937. }
  938. /*
  939. // 导入PPTX文件
  940. const importPPTXFile = (files: FileList, options?: { cover?: boolean; fixedViewport?: boolean; signal?: AbortSignal }) => {
  941. console.log('导入', files)
  942. const defaultOptions = {
  943. cover: false,
  944. fixedViewport: false,
  945. }
  946. const { cover, fixedViewport, signal } = { ...defaultOptions, ...options }
  947. const file = files[0]
  948. if (!file) return
  949. exporting.value = true
  950. const shapeList: ShapePoolItem[] = []
  951. for (const item of SHAPE_LIST) {
  952. shapeList.push(...item.children)
  953. }
  954. const reader = new FileReader()
  955. reader.onload = async (e: ProgressEvent<FileReader>) => {
  956. // 检查是否已取消
  957. if (signal?.aborted) {
  958. exporting.value = false
  959. return
  960. }
  961. let json = null
  962. try {
  963. json = await parse(e.target!.result as ArrayBuffer)
  964. }
  965. catch (error) {
  966. exporting.value = false
  967. console.log('导入PPTX文件失败:', error)
  968. message.error('无法正确读取 / 解析该文件')
  969. return
  970. }
  971. let ratio = 96 / 72;
  972. //let ratio = 1
  973. const width = json.size.width
  974. if (fixedViewport) ratio = 1000 / width
  975. else slidesStore.setViewportSize(width * ratio)
  976. slidesStore.setTheme({ themeColors: json.themeColors })
  977. const slides: Slide[] = []
  978. for (const item of json.slides) {
  979. const { type, value } = item.fill
  980. let background: SlideBackground
  981. if (type === 'image') {
  982. background = {
  983. type: 'image',
  984. image: {
  985. src: value.picBase64,
  986. size: 'cover',
  987. },
  988. }
  989. }
  990. else if (type === 'gradient') {
  991. background = {
  992. type: 'gradient',
  993. gradient: {
  994. type: value.path === 'line' ? 'linear' : 'radial',
  995. colors: value.colors.map(item => ({
  996. ...item,
  997. pos: parseInt(item.pos),
  998. })),
  999. rotate: value.rot + 90,
  1000. },
  1001. }
  1002. }
  1003. else {
  1004. background = {
  1005. type: 'solid',
  1006. color: value || '#fff',
  1007. }
  1008. }
  1009. const slide: Slide = {
  1010. id: nanoid(10),
  1011. elements: [],
  1012. background,
  1013. remark: item.note || '',
  1014. }
  1015. const parseElements = (elements: Element[]) => {
  1016. const sortedElements = elements.sort((a, b) => a.order - b.order)
  1017. console.log(sortedElements)
  1018. for (const el of sortedElements) {
  1019. const originWidth = el.width || 1
  1020. const originHeight = el.height || 1
  1021. const originLeft = el.left
  1022. const originTop = el.top
  1023. el.width = el.width * ratio
  1024. el.height = el.height * ratio
  1025. el.left = el.left * ratio
  1026. el.top = el.top * ratio
  1027. if (el.type === 'text') {
  1028. const textEl: PPTTextElement = {
  1029. type: 'text',
  1030. id: nanoid(10),
  1031. width: el.width,
  1032. height: el.height,
  1033. left: el.left,
  1034. top: el.top,
  1035. rotate: el.rotate,
  1036. defaultFontName: theme.value.fontName,
  1037. defaultColor: theme.value.fontColor,
  1038. content: convertFontSizePtToPx(el.content, ratio),
  1039. lineHeight: 1,
  1040. outline: {
  1041. color: el.borderColor,
  1042. width: +(el.borderWidth * ratio).toFixed(2),
  1043. style: el.borderType,
  1044. },
  1045. fill: el.fill.type === 'color' ? el.fill.value : '',
  1046. vertical: el.isVertical,
  1047. }
  1048. if (el.shadow) {
  1049. textEl.shadow = {
  1050. h: el.shadow.h * ratio,
  1051. v: el.shadow.v * ratio,
  1052. blur: el.shadow.blur * ratio,
  1053. color: el.shadow.color,
  1054. }
  1055. }
  1056. slide.elements.push(textEl)
  1057. }
  1058. else if (el.type === 'image') {
  1059. const element: PPTImageElement = {
  1060. type: 'image',
  1061. id: nanoid(10),
  1062. src: el.src,
  1063. width: el.width,
  1064. height: el.height,
  1065. left: el.left,
  1066. top: el.top,
  1067. fixedRatio: true,
  1068. rotate: el.rotate,
  1069. flipH: el.isFlipH,
  1070. flipV: el.isFlipV,
  1071. }
  1072. if (el.borderWidth) {
  1073. element.outline = {
  1074. color: el.borderColor,
  1075. width: +(el.borderWidth * ratio).toFixed(2),
  1076. style: el.borderType,
  1077. }
  1078. }
  1079. const clipShapeTypes = ['roundRect', 'ellipse', 'triangle', 'rhombus', 'pentagon', 'hexagon', 'heptagon', 'octagon', 'parallelogram', 'trapezoid']
  1080. if (el.rect) {
  1081. element.clip = {
  1082. shape: (el.geom && clipShapeTypes.includes(el.geom)) ? el.geom : 'rect',
  1083. range: [
  1084. [
  1085. el.rect.l || 0,
  1086. el.rect.t || 0,
  1087. ],
  1088. [
  1089. 100 - (el.rect.r || 0),
  1090. 100 - (el.rect.b || 0),
  1091. ],
  1092. ]
  1093. }
  1094. }
  1095. else if (el.geom && clipShapeTypes.includes(el.geom)) {
  1096. element.clip = {
  1097. shape: el.geom,
  1098. range: [[0, 0], [100, 100]]
  1099. }
  1100. }
  1101. slide.elements.push(element)
  1102. }
  1103. else if (el.type === 'math') {
  1104. slide.elements.push({
  1105. type: 'image',
  1106. id: nanoid(10),
  1107. src: el.picBase64,
  1108. width: el.width,
  1109. height: el.height,
  1110. left: el.left,
  1111. top: el.top,
  1112. fixedRatio: true,
  1113. rotate: 0,
  1114. })
  1115. }
  1116. else if (el.type === 'audio') {
  1117. slide.elements.push({
  1118. type: 'audio',
  1119. id: nanoid(10),
  1120. src: el.blob,
  1121. width: el.width,
  1122. height: el.height,
  1123. left: el.left,
  1124. top: el.top,
  1125. rotate: 0,
  1126. fixedRatio: false,
  1127. color: theme.value.themeColors[0],
  1128. loop: false,
  1129. autoplay: false,
  1130. })
  1131. }
  1132. else if (el.type === 'video') {
  1133. slide.elements.push({
  1134. type: 'video',
  1135. id: nanoid(10),
  1136. src: (el.blob || el.src)!,
  1137. width: el.width,
  1138. height: el.height,
  1139. left: el.left,
  1140. top: el.top,
  1141. rotate: 0,
  1142. autoplay: false,
  1143. })
  1144. }
  1145. else if (el.type === 'shape') {
  1146. if (el.shapType === 'line' || /Connector/.test(el.shapType)) {
  1147. const lineElement = parseLineElement(el, ratio)
  1148. slide.elements.push(lineElement)
  1149. }
  1150. else {
  1151. const shape = shapeList.find(item => item.pptxShapeType === el.shapType)
  1152. const vAlignMap: { [key: string]: ShapeTextAlign } = {
  1153. 'mid': 'middle',
  1154. 'down': 'bottom',
  1155. 'up': 'top',
  1156. }
  1157. const gradient: Gradient | undefined = el.fill?.type === 'gradient' ? {
  1158. type: el.fill.value.path === 'line' ? 'linear' : 'radial',
  1159. colors: el.fill.value.colors.map(item => ({
  1160. ...item,
  1161. pos: parseInt(item.pos),
  1162. })),
  1163. rotate: el.fill.value.rot,
  1164. } : undefined
  1165. const pattern: string | undefined = el.fill?.type === 'image' ? el.fill.value.picBase64 : undefined
  1166. const fill = el.fill?.type === 'color' ? el.fill.value : ''
  1167. const element: PPTShapeElement = {
  1168. type: 'shape',
  1169. id: nanoid(10),
  1170. width: el.width,
  1171. height: el.height,
  1172. left: el.left,
  1173. top: el.top,
  1174. viewBox: [200, 200],
  1175. path: 'M 0 0 L 200 0 L 200 200 L 0 200 Z',
  1176. fill,
  1177. gradient,
  1178. pattern,
  1179. fixedRatio: false,
  1180. rotate: el.rotate,
  1181. outline: {
  1182. color: el.borderColor,
  1183. width: +(el.borderWidth * ratio).toFixed(2),
  1184. style: el.borderType,
  1185. },
  1186. text: {
  1187. content: convertFontSizePtToPx(el.content, ratio),
  1188. defaultFontName: theme.value.fontName,
  1189. defaultColor: theme.value.fontColor,
  1190. align: vAlignMap[el.vAlign] || 'middle',
  1191. },
  1192. flipH: el.isFlipH,
  1193. flipV: el.isFlipV,
  1194. }
  1195. if (el.shadow) {
  1196. element.shadow = {
  1197. h: el.shadow.h * ratio,
  1198. v: el.shadow.v * ratio,
  1199. blur: el.shadow.blur * ratio,
  1200. color: el.shadow.color,
  1201. }
  1202. }
  1203. if (shape) {
  1204. element.path = shape.path
  1205. element.viewBox = shape.viewBox
  1206. if (shape.pathFormula) {
  1207. element.pathFormula = shape.pathFormula
  1208. element.viewBox = [el.width, el.height]
  1209. const pathFormula = SHAPE_PATH_FORMULAS[shape.pathFormula]
  1210. if ('editable' in pathFormula && pathFormula.editable) {
  1211. element.path = pathFormula.formula(el.width, el.height, pathFormula.defaultValue)
  1212. element.keypoints = pathFormula.defaultValue
  1213. }
  1214. else element.path = pathFormula.formula(el.width, el.height)
  1215. }
  1216. }
  1217. else if (el.path && el.path.indexOf('NaN') === -1) {
  1218. const { maxX, maxY } = getSvgPathRange(el.path)
  1219. element.path = el.path
  1220. element.viewBox = [maxX || originWidth, maxY || originHeight]
  1221. }
  1222. if (el.shapType === 'custom') {
  1223. if (el.path!.indexOf('NaN') !== -1) {
  1224. if (element.width === 0) element.width = 0.1
  1225. if (element.height === 0) element.height = 0.1
  1226. element.path = el.path!.replace(/NaN/g, '0')
  1227. }
  1228. else {
  1229. element.special = true
  1230. element.path = el.path!
  1231. }
  1232. const { maxX, maxY } = getSvgPathRange(element.path)
  1233. element.viewBox = [maxX || originWidth, maxY || originHeight]
  1234. }
  1235. if (element.path) slide.elements.push(element)
  1236. }
  1237. }
  1238. else if (el.type === 'table') {
  1239. const row = el.data.length
  1240. const col = el.data[0].length
  1241. const style: TableCellStyle = {
  1242. fontname: theme.value.fontName,
  1243. color: theme.value.fontColor,
  1244. }
  1245. const data: TableCell[][] = []
  1246. for (let i = 0; i < row; i++) {
  1247. const rowCells: TableCell[] = []
  1248. for (let j = 0; j < col; j++) {
  1249. const cellData = el.data[i][j]
  1250. let textDiv: HTMLDivElement | null = document.createElement('div')
  1251. textDiv.innerHTML = cellData.text
  1252. const p = textDiv.querySelector('p')
  1253. const align = p?.style.textAlign || 'left'
  1254. const span = textDiv.querySelector('span')
  1255. const fontsize = span?.style.fontSize ? (parseInt(span?.style.fontSize) * ratio).toFixed(1) + 'px' : ''
  1256. const fontname = span?.style.fontFamily || ''
  1257. const color = span?.style.color || cellData.fontColor
  1258. rowCells.push({
  1259. id: nanoid(10),
  1260. colspan: cellData.colSpan || 1,
  1261. rowspan: cellData.rowSpan || 1,
  1262. text: textDiv.innerText,
  1263. style: {
  1264. ...style,
  1265. align: ['left', 'right', 'center'].includes(align) ? (align as 'left' | 'right' | 'center') : 'left',
  1266. fontsize,
  1267. fontname,
  1268. color,
  1269. bold: cellData.fontBold,
  1270. backcolor: cellData.fillColor,
  1271. },
  1272. })
  1273. textDiv = null
  1274. }
  1275. data.push(rowCells)
  1276. }
  1277. const allWidth = el.colWidths.reduce((a, b) => a + b, 0)
  1278. const colWidths: number[] = el.colWidths.map(item => item / allWidth)
  1279. const firstCell = el.data[0][0]
  1280. const border = firstCell.borders.top ||
  1281. firstCell.borders.bottom ||
  1282. el.borders.top ||
  1283. el.borders.bottom ||
  1284. firstCell.borders.left ||
  1285. firstCell.borders.right ||
  1286. el.borders.left ||
  1287. el.borders.right
  1288. const borderWidth = border?.borderWidth || 0
  1289. const borderStyle = border?.borderType || 'solid'
  1290. const borderColor = border?.borderColor || '#eeece1'
  1291. slide.elements.push({
  1292. type: 'table',
  1293. id: nanoid(10),
  1294. width: el.width,
  1295. height: el.height,
  1296. left: el.left,
  1297. top: el.top,
  1298. colWidths,
  1299. rotate: 0,
  1300. data,
  1301. outline: {
  1302. width: +(borderWidth * ratio || 2).toFixed(2),
  1303. style: borderStyle,
  1304. color: borderColor,
  1305. },
  1306. cellMinHeight: el.rowHeights[0] ? el.rowHeights[0] * ratio : 36,
  1307. })
  1308. }
  1309. else if (el.type === 'chart') {
  1310. let labels: string[]
  1311. let legends: string[]
  1312. let series: number[][]
  1313. if (el.chartType === 'scatterChart' || el.chartType === 'bubbleChart') {
  1314. labels = el.data[0].map((item, index) => `坐标${index + 1}`)
  1315. legends = ['X', 'Y']
  1316. series = el.data
  1317. }
  1318. else {
  1319. const data = el.data as ChartItem[]
  1320. labels = Object.values(data[0].xlabels)
  1321. legends = data.map(item => item.key)
  1322. series = data.map(item => item.values.map(v => v.y))
  1323. }
  1324. const options: ChartOptions = {}
  1325. let chartType: ChartType = 'bar'
  1326. switch (el.chartType) {
  1327. case 'barChart':
  1328. case 'bar3DChart':
  1329. chartType = 'bar'
  1330. if (el.barDir === 'bar') chartType = 'column'
  1331. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1332. break
  1333. case 'lineChart':
  1334. case 'line3DChart':
  1335. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1336. chartType = 'line'
  1337. break
  1338. case 'areaChart':
  1339. case 'area3DChart':
  1340. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1341. chartType = 'area'
  1342. break
  1343. case 'scatterChart':
  1344. case 'bubbleChart':
  1345. chartType = 'scatter'
  1346. break
  1347. case 'pieChart':
  1348. case 'pie3DChart':
  1349. chartType = 'pie'
  1350. break
  1351. case 'radarChart':
  1352. chartType = 'radar'
  1353. break
  1354. case 'doughnutChart':
  1355. chartType = 'ring'
  1356. break
  1357. default:
  1358. }
  1359. slide.elements.push({
  1360. type: 'chart',
  1361. id: nanoid(10),
  1362. chartType: chartType,
  1363. width: el.width,
  1364. height: el.height,
  1365. left: el.left,
  1366. top: el.top,
  1367. rotate: 0,
  1368. themeColors: el.colors.length ? el.colors : theme.value.themeColors,
  1369. textColor: theme.value.fontColor,
  1370. data: {
  1371. labels,
  1372. legends,
  1373. series,
  1374. },
  1375. options,
  1376. })
  1377. }
  1378. else if (el.type === 'group') {
  1379. let elements: BaseElement[] = el.elements.map(_el => {
  1380. let left = _el.left + originLeft
  1381. let top = _el.top + originTop
  1382. if (el.rotate) {
  1383. const { x, y } = calculateRotatedPosition(originLeft, originTop, originWidth, originHeight, _el.left, _el.top, el.rotate)
  1384. left = x
  1385. top = y
  1386. }
  1387. const element = {
  1388. ..._el,
  1389. left,
  1390. top,
  1391. }
  1392. if (el.isFlipH && 'isFlipH' in element) element.isFlipH = true
  1393. if (el.isFlipV && 'isFlipV' in element) element.isFlipV = true
  1394. return element
  1395. })
  1396. if (el.isFlipH) elements = flipGroupElements(elements, 'y')
  1397. if (el.isFlipV) elements = flipGroupElements(elements, 'x')
  1398. parseElements(elements)
  1399. }
  1400. else if (el.type === 'diagram') {
  1401. const elements = el.elements.map(_el => ({
  1402. ..._el,
  1403. left: _el.left + originLeft,
  1404. top: _el.top + originTop,
  1405. }))
  1406. parseElements(elements)
  1407. }
  1408. }
  1409. }
  1410. parseElements([...item.elements, ...item.layoutElements])
  1411. slides.push(slide)
  1412. }
  1413. if (cover) {
  1414. slidesStore.updateSlideIndex(0)
  1415. slidesStore.setSlides(slides)
  1416. addHistorySnapshot()
  1417. }
  1418. else if (isEmptySlide.value) {
  1419. slidesStore.setSlides(slides)
  1420. addHistorySnapshot()
  1421. }
  1422. else addSlidesFromData(slides)
  1423. exporting.value = false
  1424. }
  1425. reader.readAsArrayBuffer(file)
  1426. // 监听取消信号
  1427. signal?.addEventListener('abort', () => {
  1428. reader.abort()
  1429. exporting.value = false
  1430. })
  1431. // 监听取消信号
  1432. signal?.addEventListener('abort', () => {
  1433. reader.abort()
  1434. exporting.value = false
  1435. })
  1436. }
  1437. */
  1438. const importPPTXFile = (files: FileList, options?: { cover?: boolean; fixedViewport?: boolean; signal?: AbortSignal, onclose?: () => void }) => {
  1439. console.log('导入', files)
  1440. const defaultOptions = {
  1441. cover: false,
  1442. fixedViewport: false,
  1443. }
  1444. const { cover, fixedViewport, signal, onclose } = { ...defaultOptions, ...options }
  1445. let isNone = false
  1446. if (slides.value.length === 1 && slides.value[0].elements.length === 0) {
  1447. isNone = true
  1448. }
  1449. const file = files[0]
  1450. if (!file) return
  1451. exporting.value = true // 假设 exporting 是一个全局 ref
  1452. imgExporting.value = true // 假设 imgExporting 是一个全局 ref
  1453. // 预加载形状库(用于后续形状匹配)
  1454. const shapeList: ShapePoolItem[] = []
  1455. for (const item of SHAPE_LIST) {
  1456. shapeList.push(...item.children)
  1457. }
  1458. const reader = new FileReader()
  1459. reader.onload = async (e: ProgressEvent<FileReader>) => {
  1460. // 检查是否已取消
  1461. if (signal?.aborted) {
  1462. exporting.value = false
  1463. imgExporting.value = false
  1464. return
  1465. }
  1466. let json = null
  1467. try {
  1468. json = await parse(e.target!.result as ArrayBuffer)
  1469. }
  1470. catch (error) {
  1471. exporting.value = false
  1472. imgExporting.value = false
  1473. console.log('导入PPTX文件失败:', error)
  1474. message.error(lang.ssFileReadFail)
  1475. return
  1476. }
  1477. if (signal?.aborted) {
  1478. exporting.value = false
  1479. imgExporting.value = false
  1480. return
  1481. }
  1482. // 计算缩放比例
  1483. let ratio = 96 / 72 // PPTX 默认 72 DPI,屏幕 96 DPI
  1484. const width = json.size.width
  1485. const height = json.size.height
  1486. const viewportRatio = json.size.viewportRatio || (height && width ? height / width : undefined)
  1487. if (fixedViewport) {
  1488. ratio = 1000 / width // 固定视口宽度为 1000px
  1489. }
  1490. else {
  1491. const targetViewportSize = width * ratio
  1492. if (!isNone && targetViewportSize != slidesStore.viewportSize) {
  1493. const confirmed = await showConfirmDialog({
  1494. title: lang.ssConfirmOperation,
  1495. content: lang.ssPageSizeMismatch,
  1496. confirmText: lang.ssConfirm,
  1497. cancelText: lang.ssCancel
  1498. })
  1499. if (!confirmed) {
  1500. exporting.value = false
  1501. imgExporting.value = false
  1502. onclose?.()
  1503. return Promise.reject(new Error('用户取消导入'))
  1504. }
  1505. }
  1506. if (isNone || targetViewportSize > slidesStore.viewportSize) {
  1507. slidesStore.setViewportSize(targetViewportSize) // 调整画布大小
  1508. slidesStore.setViewportRatio(viewportRatio)
  1509. }
  1510. }
  1511. // 设置主题色
  1512. slidesStore.setTheme({ themeColors: json.themeColors })
  1513. const slides: Slide[] = []
  1514. // 收集当前幻灯片内所有上传任务
  1515. const uploadTasks: Promise<void>[] = []
  1516. // 遍历每一张幻灯片
  1517. for (const item of json.slides) {
  1518. // ----- 解析背景 -----
  1519. const { type, value } = item.fill
  1520. let background: SlideBackground
  1521. if (type === 'image') {
  1522. // 背景图片也可能需要上传(但 PPTX 背景图通常是内嵌 base64)
  1523. // 这里为了简化,暂不处理背景图片上传,如有需要可类似元素上传
  1524. background = {
  1525. type: 'image',
  1526. image: {
  1527. src: value.picBase64,
  1528. size: 'cover',
  1529. },
  1530. }
  1531. }
  1532. else if (type === 'gradient') {
  1533. background = {
  1534. type: 'gradient',
  1535. gradient: {
  1536. type: value.path === 'line' ? 'linear' : 'radial',
  1537. colors: value.colors.map(item => ({
  1538. ...item,
  1539. pos: parseInt(item.pos),
  1540. })),
  1541. rotate: value.rot + 90,
  1542. },
  1543. }
  1544. }
  1545. else {
  1546. background = {
  1547. type: 'solid',
  1548. color: value || '#fff',
  1549. }
  1550. }
  1551. const slide: Slide = {
  1552. id: nanoid(10),
  1553. elements: [],
  1554. background,
  1555. remark: item.note || '',
  1556. }
  1557. // ----- 解析元素(递归函数)-----
  1558. const parseElements = async (elements: any[], pelements: any = null) => {
  1559. // 按绘制顺序排序
  1560. const sortedElements = elements.sort((a, b) => a.order - b.order)
  1561. console.log(sortedElements)
  1562. for (const el of sortedElements) {
  1563. // 保存原始尺寸用于后续可能的路径计算
  1564. const originWidth = el.width || 1
  1565. const originHeight = el.height || 1
  1566. const originLeft = el.left
  1567. const originTop = el.top
  1568. // 保存原始尺寸用于后续可能的路径计算
  1569. const poriginWidth = pelements?.width
  1570. const poriginHeight = pelements?.height
  1571. const poriginLeft = pelements?.left
  1572. const poriginTop = pelements?.top
  1573. // 应用缩放
  1574. el.width = el.width * ratio
  1575. el.height = el.height * ratio
  1576. el.left = el.left * ratio
  1577. el.top = el.top * ratio
  1578. if (el.type === 'text') {
  1579. const vAlignMap: { [key: string]: ShapeTextAlign } = {
  1580. mid: 'middle',
  1581. down: 'bottom',
  1582. up: 'top',
  1583. }
  1584. const textEl: PPTTextElement = {
  1585. type: 'text',
  1586. id: nanoid(10),
  1587. width: el.width,
  1588. height: el.height,
  1589. left: el.left,
  1590. top: el.top,
  1591. rotate: el.rotate,
  1592. defaultFontName: theme.value.fontName,
  1593. defaultColor: theme.value.fontColor,
  1594. content: convertFontSizePtToPx(el.content, ratio, el.autoFit),
  1595. style: getStyle(convertFontSizePtToPx(el.content, ratio, el.autoFit)),
  1596. lineHeight: 1.5,
  1597. align: vAlignMap[el.vAlign] || 'middle',
  1598. outline: {
  1599. color: el.borderColor,
  1600. width: +(el.borderWidth * ratio).toFixed(2),
  1601. style: el.borderType,
  1602. },
  1603. fill: el.fill.type === 'color' ? el.fill.value : '',
  1604. vertical: el.isVertical,
  1605. }
  1606. if (el.shadow) {
  1607. textEl.shadow = {
  1608. h: el.shadow.h * ratio,
  1609. v: el.shadow.v * ratio,
  1610. blur: el.shadow.blur * ratio,
  1611. color: el.shadow.color,
  1612. }
  1613. }
  1614. slide.elements.push(textEl)
  1615. }
  1616. // ---------- 图片 ----------
  1617. if (el.type === 'image') {
  1618. const element: PPTImageElement = {
  1619. type: 'image',
  1620. id: nanoid(10),
  1621. src: el.src, // 可能是 base64 或已有 URL
  1622. width: el.width,
  1623. height: el.height,
  1624. left: el.left,
  1625. top: el.top,
  1626. fixedRatio: true,
  1627. rotate: el.rotate,
  1628. flipH: el.isFlipH,
  1629. flipV: el.isFlipV,
  1630. }
  1631. // 边框
  1632. if (el.borderWidth) {
  1633. element.outline = {
  1634. color: el.borderColor,
  1635. width: +(el.borderWidth * ratio).toFixed(2),
  1636. style: el.borderType,
  1637. }
  1638. }
  1639. // 裁剪(形状剪裁)
  1640. const clipShapeTypes = ['roundRect', 'ellipse', 'triangle', 'rhombus', 'pentagon', 'hexagon', 'heptagon', 'octagon', 'parallelogram', 'trapezoid']
  1641. if (el.rect) {
  1642. element.clip = {
  1643. shape: (el.geom && clipShapeTypes.includes(el.geom)) ? el.geom : 'rect',
  1644. range: [
  1645. [el.rect.l || 0, el.rect.t || 0],
  1646. [100 - (el.rect.r || 0), 100 - (el.rect.b || 0)],
  1647. ],
  1648. }
  1649. }
  1650. else if (el.geom && clipShapeTypes.includes(el.geom)) {
  1651. element.clip = {
  1652. shape: el.geom,
  1653. range: [[0, 0], [100, 100]],
  1654. }
  1655. }
  1656. // 如果 src 是 base64,触发上传
  1657. if (el.src && typeof el.src === 'string' && el.src.startsWith('blob:')) {
  1658. const uploadTask = (async () => {
  1659. try {
  1660. const file = await makeWhiteTransparent(el.src, `image_${Date.now()}.png`)
  1661. if (file) {
  1662. const url = await uploadFileToS3(file)
  1663. element.src = url // 替换为远程 URL
  1664. const slidesStore = useSlidesStore()
  1665. slidesStore.updateElement({ id: element.id, props: { src: url } })
  1666. }
  1667. }
  1668. catch (error) {
  1669. console.error('Image upload failed:', error)
  1670. // 失败时保留原 base64(或可置空)
  1671. }
  1672. })()
  1673. uploadTasks.push(uploadTask)
  1674. }
  1675. slide.elements.push(element)
  1676. }
  1677. else if (el.type === 'math') {
  1678. const element: PPTImageElement = {
  1679. type: 'image',
  1680. id: nanoid(10),
  1681. src: el.picBase64,
  1682. width: el.width,
  1683. height: el.height,
  1684. left: el.left,
  1685. top: el.top,
  1686. fixedRatio: true,
  1687. rotate: 0,
  1688. }
  1689. // 如果 src 是 base64,触发上传
  1690. if (el.picBase64 && typeof el.picBase64 === 'string' && el.picBase64.startsWith('blob:')) {
  1691. const uploadTask = (async () => {
  1692. try {
  1693. const file = makeWhiteTransparent(el.picBase64, `image_${Date.now()}.png`)
  1694. if (file) {
  1695. const url = await uploadFileToS3(file)
  1696. element.src = url // 替换为远程 URL
  1697. const slidesStore = useSlidesStore()
  1698. slidesStore.updateElement({ id: element.id, props: { src: url } })
  1699. }
  1700. }
  1701. catch (error) {
  1702. console.error('Image upload failed:', error)
  1703. // 失败时保留原 base64(或可置空)
  1704. }
  1705. })()
  1706. uploadTasks.push(uploadTask)
  1707. }
  1708. slide.elements.push(element)
  1709. }
  1710. // ---------- 音频 ----------
  1711. else if (el.type === 'audio') {
  1712. const element: PPTAudioElement = {
  1713. type: 'audio',
  1714. id: nanoid(10),
  1715. src: el.blob,
  1716. width: el.width,
  1717. height: el.height,
  1718. left: el.left,
  1719. top: el.top,
  1720. rotate: 0,
  1721. fixedRatio: false,
  1722. color: theme.value.themeColors[0],
  1723. loop: false,
  1724. autoplay: false,
  1725. }
  1726. const localData = el.blob || (el.src && typeof el.src === 'string' && el.src.startsWith('data:') ? el.src : null)
  1727. if (localData) {
  1728. const uploadTask = (async () => {
  1729. try {
  1730. const file = await dataToFile(localData, `audio_${Date.now()}.mp3`, 'audio/mpeg')
  1731. if (file) {
  1732. const url = await uploadFileToS3(file)
  1733. element.src = url
  1734. const slidesStore = useSlidesStore()
  1735. slidesStore.updateElement({ id: element.id, props: { src: url } })
  1736. }
  1737. }
  1738. catch (error) {
  1739. console.error('Audio upload failed:', error)
  1740. }
  1741. })()
  1742. uploadTasks.push(uploadTask)
  1743. }
  1744. slide.elements.push(element)
  1745. }
  1746. // ---------- 视频 ----------
  1747. else if (el.type === 'video') {
  1748. const element: PPTVideoElement = {
  1749. type: 'video',
  1750. id: nanoid(10),
  1751. src: (el.blob || el.src)!,
  1752. width: el.width,
  1753. height: el.height,
  1754. left: el.left,
  1755. top: el.top,
  1756. rotate: 0,
  1757. autoplay: false,
  1758. }
  1759. const localData = el.blob || (el.src && typeof el.src === 'string' && el.src.startsWith('data:') ? el.src : null)
  1760. if (localData) {
  1761. const uploadTask = (async () => {
  1762. try {
  1763. const file = await dataToFile(localData, `video_${Date.now()}.mp4`, 'video/mp4')
  1764. if (file) {
  1765. const url = await uploadFileToS3(file)
  1766. element.src = url
  1767. const slidesStore = useSlidesStore()
  1768. slidesStore.updateElement({ id: element.id, props: { src: url } })
  1769. }
  1770. }
  1771. catch (error) {
  1772. console.error('Video upload failed:', error)
  1773. }
  1774. })()
  1775. uploadTasks.push(uploadTask)
  1776. }
  1777. slide.elements.push(element)
  1778. }
  1779. // ---------- 形状 ----------
  1780. else if (el.type === 'shape') {
  1781. if (el.shapType === 'line' || /Connector/.test(el.shapType)) {
  1782. // 线条元素(单独处理)
  1783. const lineElement = parseLineElement(el, ratio)
  1784. slide.elements.push(lineElement)
  1785. }
  1786. else {
  1787. const shape = shapeList.find(item => item.pptxShapeType === el.shapType)
  1788. const vAlignMap: { [key: string]: ShapeTextAlign } = {
  1789. mid: 'middle',
  1790. down: 'bottom',
  1791. up: 'top',
  1792. }
  1793. const gradient: Gradient | undefined = el.fill?.type === 'gradient'
  1794. ? {
  1795. type: el.fill.value.path === 'line' ? 'linear' : 'radial',
  1796. colors: el.fill.value.colors.map(item => ({
  1797. ...item,
  1798. pos: parseInt(item.pos),
  1799. })),
  1800. rotate: el.fill.value.rot,
  1801. }
  1802. : undefined
  1803. const pattern: string | undefined = el.fill?.type === 'image' ? el.fill.value.picBase64 : undefined
  1804. const fill = el.fill?.type === 'color' ? el.fill.value : 'none'
  1805. const style = getStyle(convertFontSizePtToPx(el.content, ratio, el.autoFit)) + (el.pathBBox?.pWidth ? ';width:' + (el.pathBBox?.pWidth * ratio) + 'px;height:' + (el.pathBBox?.pHeight * ratio) + 'px;' : '') // 设置字体的样式等,这里由于不支持的样式在里面会过滤
  1806. const element: PPTShapeElement = {
  1807. type: 'shape',
  1808. id: nanoid(10),
  1809. width: el.width,
  1810. height: el.height,
  1811. left: el.left,
  1812. top: el.top,
  1813. viewBox: [200, 200],
  1814. path: 'M 0 0 L 200 0 L 200 200 L 0 200 Z',
  1815. fill,
  1816. gradient,
  1817. pattern,
  1818. fixedRatio: false,
  1819. rotate: el.rotate,
  1820. pathBBox: el.pathBBox,
  1821. outline: {
  1822. color: el.borderColor,
  1823. width: +(el.borderWidth * ratio).toFixed(2),
  1824. style: el.borderType,
  1825. },
  1826. text: {
  1827. content: convertFontSizePtToPx(el.content, ratio, el.autoFit),
  1828. style: style,
  1829. defaultFontName: theme.value.fontName,
  1830. defaultColor: theme.value.fontColor,
  1831. align: vAlignMap[el.vAlign] || 'middle',
  1832. },
  1833. flipH: el.isFlipH,
  1834. flipV: el.isFlipV,
  1835. }
  1836. if (el.shadow) {
  1837. element.shadow = {
  1838. h: el.shadow.h * ratio,
  1839. v: el.shadow.v * ratio,
  1840. blur: el.shadow.blur * ratio,
  1841. color: el.shadow.color,
  1842. }
  1843. }
  1844. if (shape) {
  1845. const { maxX, maxY } = getSvgPathRange(el.path)
  1846. element.path = el.path
  1847. element.viewBox = poriginWidth ? [maxX, maxY] : [originWidth, originHeight]
  1848. /*
  1849. if (shape.pathFormula) {
  1850. element.pathFormula = shape.pathFormula
  1851. element.viewBox = [el.width, el.height]
  1852. // element.viewBox = [poriginWidth || originWidth || maxX, poriginHeight || originHeight || maxY];
  1853. const pathFormula = SHAPE_PATH_FORMULAS[shape.pathFormula]
  1854. if ('editable' in pathFormula && pathFormula.editable) {
  1855. element.path = pathFormula.formula(el.width, el.height, pathFormula.defaultValue)
  1856. element.keypoints = pathFormula.defaultValue
  1857. }
  1858. else {
  1859. element.path = pathFormula.formula(el.width, el.height)
  1860. }
  1861. }
  1862. */
  1863. }
  1864. else if (el.path && el.path.indexOf('NaN') === -1) {
  1865. const { maxX, maxY } = getSvgPathRange(el.path)
  1866. element.path = el.path
  1867. element.viewBox = poriginWidth ? [maxX, maxY] : [originWidth, originHeight]
  1868. // element.viewBox = [originWidth || maxX, originHeight || maxY];
  1869. // element.viewBox = originWidth? [(originWidth/(poriginWidth||1)), (originHeight/(poriginHeight||1))] : [maxX, maxY];
  1870. // element.viewBox = [poriginWidth || maxX, poriginHeight || maxY];
  1871. }
  1872. if (el.shapType === 'custom') {
  1873. if (el.path!.indexOf('NaN') !== -1) {
  1874. if (element.width === 0) element.width = 0.1
  1875. if (element.height === 0) element.height = 0.1
  1876. element.path = el.path!.replace(/NaN/g, '0')
  1877. }
  1878. const { maxX, maxY } = getSvgPathRange(element.path)
  1879. element.viewBox = poriginWidth ? [maxX, maxY] : [originWidth, originHeight]
  1880. // element.viewBox = [originWidth || maxX, originHeight || maxY];
  1881. // element.viewBox = [poriginWidth || originWidth || maxX, poriginHeight || originHeight || maxY];
  1882. // element.viewBox = [poriginWidth || originWidth || maxX, poriginHeight || originHeight || maxY];
  1883. // element.viewBox = [Math.max(maxX, originWidth), Math.max(maxY, originHeight)];
  1884. // element.viewBox = [originWidth, originHeight];
  1885. }
  1886. if (element.path) slide.elements.push(element)
  1887. }
  1888. }
  1889. // ---------- 表格 ----------
  1890. else if (el.type === 'table') {
  1891. const row = el.data.length
  1892. const col = el.data[0].length
  1893. const style: TableCellStyle = {
  1894. fontname: theme.value.fontName,
  1895. color: theme.value.fontColor,
  1896. }
  1897. const data: TableCell[][] = []
  1898. for (let i = 0; i < row; i++) {
  1899. const rowCells: TableCell[] = []
  1900. for (let j = 0; j < col; j++) {
  1901. const cellData = el.data[i][j]
  1902. let textDiv: HTMLDivElement | null = document.createElement('div')
  1903. textDiv.innerHTML = cellData.text
  1904. const p = textDiv.querySelector('p')
  1905. const align = p?.style.textAlign || 'left'
  1906. const span = textDiv.querySelector('span')
  1907. const fontsize = span?.style.fontSize
  1908. ? (parseInt(span?.style.fontSize) * ratio).toFixed(1) + 'px'
  1909. : ''
  1910. const fontname = span?.style.fontFamily || ''
  1911. const color = span?.style.color || cellData.fontColor
  1912. rowCells.push({
  1913. id: nanoid(10),
  1914. colspan: cellData.colSpan || 1,
  1915. rowspan: cellData.rowSpan || 1,
  1916. text: textDiv.innerText,
  1917. style: {
  1918. ...style,
  1919. align: ['left', 'right', 'center'].includes(align) ? (align as 'left' | 'right' | 'center') : 'left',
  1920. fontsize,
  1921. fontname,
  1922. color,
  1923. bold: cellData.fontBold,
  1924. backcolor: cellData.fillColor,
  1925. },
  1926. })
  1927. textDiv = null
  1928. }
  1929. data.push(rowCells)
  1930. }
  1931. const allWidth = el.colWidths.reduce((a, b) => a + b, 0)
  1932. const colWidths: number[] = el.colWidths.map(item => item / allWidth)
  1933. const firstCell = el.data[0][0]
  1934. const border = firstCell.borders.top ||
  1935. firstCell.borders.bottom ||
  1936. el.borders.top ||
  1937. el.borders.bottom ||
  1938. firstCell.borders.left ||
  1939. firstCell.borders.right ||
  1940. el.borders.left ||
  1941. el.borders.right
  1942. const borderWidth = border?.borderWidth || 0
  1943. const borderStyle = border?.borderType || 'solid'
  1944. const borderColor = border?.borderColor || '#eeece1'
  1945. slide.elements.push({
  1946. type: 'table',
  1947. id: nanoid(10),
  1948. width: el.width,
  1949. height: el.height,
  1950. left: el.left,
  1951. top: el.top,
  1952. colWidths,
  1953. rotate: 0,
  1954. data,
  1955. outline: {
  1956. width: +(borderWidth * ratio || 2).toFixed(2),
  1957. style: borderStyle,
  1958. color: borderColor,
  1959. },
  1960. cellMinHeight: el.rowHeights[0] ? el.rowHeights[0] * ratio : 36,
  1961. })
  1962. }
  1963. // ---------- 图表 ----------
  1964. else if (el.type === 'chart') {
  1965. let labels: string[]
  1966. let legends: string[]
  1967. let series: number[][]
  1968. if (el.chartType === 'scatterChart' || el.chartType === 'bubbleChart') {
  1969. labels = el.data[0].map((_, index) => lang.ssCoord.replace(/\*/g, (index + 1)))
  1970. legends = ['X', 'Y']
  1971. series = el.data
  1972. }
  1973. else {
  1974. const data = el.data as ChartItem[]
  1975. labels = Object.values(data[0].xlabels)
  1976. legends = data.map(item => item.key)
  1977. series = data.map(item => item.values.map(v => v.y))
  1978. }
  1979. const options: ChartOptions = {}
  1980. let chartType: ChartType = 'bar'
  1981. switch (el.chartType) {
  1982. case 'barChart':
  1983. case 'bar3DChart':
  1984. chartType = 'bar'
  1985. if (el.barDir === 'bar') chartType = 'column'
  1986. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1987. break
  1988. case 'lineChart':
  1989. case 'line3DChart':
  1990. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1991. chartType = 'line'
  1992. break
  1993. case 'areaChart':
  1994. case 'area3DChart':
  1995. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1996. chartType = 'area'
  1997. break
  1998. case 'scatterChart':
  1999. case 'bubbleChart':
  2000. chartType = 'scatter'
  2001. break
  2002. case 'pieChart':
  2003. case 'pie3DChart':
  2004. chartType = 'pie'
  2005. break
  2006. case 'radarChart':
  2007. chartType = 'radar'
  2008. break
  2009. case 'doughnutChart':
  2010. chartType = 'ring'
  2011. break
  2012. default:
  2013. }
  2014. slide.elements.push({
  2015. type: 'chart',
  2016. id: nanoid(10),
  2017. chartType,
  2018. width: el.width,
  2019. height: el.height,
  2020. left: el.left,
  2021. top: el.top,
  2022. rotate: 0,
  2023. themeColors: el.colors.length ? el.colors : theme.value.themeColors,
  2024. textColor: theme.value.fontColor,
  2025. data: {
  2026. labels,
  2027. legends,
  2028. series,
  2029. },
  2030. options,
  2031. })
  2032. }
  2033. // ---------- 组合 ----------
  2034. else if (el.type === 'group') {
  2035. // 先将子元素坐标转换到画布绝对坐标
  2036. let elements: BaseElement[] = el.elements.map((_el: any) => {
  2037. let left = _el.left + originLeft
  2038. let top = _el.top + originTop
  2039. if (el.rotate) {
  2040. const { x, y } = calculateRotatedPosition(
  2041. originLeft, originTop, originWidth, originHeight,
  2042. _el.left, _el.top, el.rotate
  2043. )
  2044. left = x
  2045. top = y
  2046. }
  2047. const element = {
  2048. ..._el,
  2049. left,
  2050. top,
  2051. }
  2052. if (el.isFlipH && 'isFlipH' in element) element.isFlipH = true
  2053. if (el.isFlipV && 'isFlipV' in element) element.isFlipV = true
  2054. return element
  2055. })
  2056. if (el.isFlipH) elements = flipGroupElements(elements, 'y')
  2057. if (el.isFlipV) elements = flipGroupElements(elements, 'x')
  2058. // 递归解析子元素(注意:子元素的上传任务会加入同一个 uploadTasks 数组)
  2059. await parseElements(elements, el)
  2060. }
  2061. // ---------- 图表组合(SmartArt)----------
  2062. else if (el.type === 'diagram') {
  2063. const elements = el.elements.map((_el: any) => ({
  2064. ..._el,
  2065. left: _el.left + originLeft,
  2066. top: _el.top + originTop,
  2067. }))
  2068. await parseElements(elements, el)
  2069. }
  2070. }
  2071. }
  2072. // 开始解析当前幻灯片的所有元素(包括布局元素)
  2073. await parseElements([...item.elements, ...item.layoutElements])
  2074. // 幻灯片构建完成,加入数组
  2075. slides.push(slide)
  2076. }
  2077. // 根据选项将幻灯片插入 store
  2078. if (cover) {
  2079. slidesStore.updateSlideIndex(0)
  2080. slidesStore.setSlides(slides)
  2081. addHistorySnapshot()
  2082. }
  2083. else if (isEmptySlide.value) {
  2084. slidesStore.setSlides(slides)
  2085. addHistorySnapshot()
  2086. }
  2087. else {
  2088. addSlidesFromData(slides)
  2089. }
  2090. // 等待当前幻灯片内所有上传任务完成
  2091. // await Promise.all(uploadTasks)
  2092. Promise.all(uploadTasks).then(() => {
  2093. imgExporting.value = false
  2094. }).catch(() => {
  2095. imgExporting.value = false
  2096. })
  2097. exporting.value = false
  2098. onclose?.()
  2099. /*
  2100. // 更新视口尺寸(如果提供了的话)
  2101. if (width !== undefined && height !== undefined) {
  2102. console.log('正在触发视口尺寸更新事件:', { width, height, viewportRatio })
  2103. // 同时也要更新slidesStore中的相关数据
  2104. if (slidesStore.setViewportSize) {
  2105. console.log('正在更新store中的视口尺寸')
  2106. slidesStore.setViewportSize(width)
  2107. if (slidesStore.setViewportRatio && viewportRatio !== undefined) {
  2108. slidesStore.setViewportRatio(viewportRatio)
  2109. console.log('视口比例已更新:', viewportRatio)
  2110. }
  2111. }
  2112. window.dispatchEvent(new CustomEvent('viewportSizeUpdated', {
  2113. detail: { width, height, viewportRatio }
  2114. }))
  2115. console.log('视口尺寸更新事件已触发')
  2116. }
  2117. // 导入成功后,触发画布尺寸更新
  2118. // 使用 nextTick 确保DOM更新完成后再触发
  2119. console.log('开始触发画布尺寸更新事件...')
  2120. nextTick(() => {
  2121. console.log('DOM更新完成,触发 slidesDataUpdated 事件')
  2122. // 触发自定义事件,通知需要更新画布尺寸的组件
  2123. window.dispatchEvent(new CustomEvent('slidesDataUpdated', {
  2124. detail: {
  2125. slides,
  2126. cover,
  2127. title,
  2128. theme,
  2129. width,
  2130. height,
  2131. viewportRatio,
  2132. timestamp: Date.now()
  2133. }
  2134. }))
  2135. console.log('slidesDataUpdated 事件已触发')
  2136. // 检查并调整幻灯片索引,确保在有效范围内
  2137. const newSlideCount = slides.length
  2138. const currentIndex = slidesStore.slideIndex
  2139. if (currentIndex >= newSlideCount) {
  2140. console.log('调整幻灯片索引:', currentIndex, '->', Math.max(0, newSlideCount - 1))
  2141. slidesStore.updateSlideIndex(Math.max(0, newSlideCount - 1))
  2142. }
  2143. console.log('画布尺寸更新事件处理完成')
  2144. })
  2145. */
  2146. }
  2147. reader.readAsArrayBuffer(file)
  2148. }
  2149. const getFile = (url: string): Promise<{ data: any }> => {
  2150. return new Promise((resolve, reject) => {
  2151. // 检查 AWS SDK 是否可用
  2152. if (typeof window !== 'undefined' && !window.AWS) {
  2153. reject(new Error('AWS SDK not available'))
  2154. return
  2155. }
  2156. const credentials = {
  2157. accessKeyId: 'AKIATLPEDU37QV5CHLMH',
  2158. secretAccessKey: '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',
  2159. } // 秘钥形式的登录上传
  2160. window.AWS.config.update(credentials)
  2161. window.AWS.config.region = 'cn-northwest-1' // 设置区域
  2162. const s3 = new window.AWS.S3({ params: { Bucket: 'ccrb' } })
  2163. // 解析文件名
  2164. const bucketUrl = 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/'
  2165. if (!url.startsWith(bucketUrl)) {
  2166. reject(new Error('Invalid S3 URL format'))
  2167. return
  2168. }
  2169. const name = decodeURIComponent(url.split(bucketUrl)[1])
  2170. // const name = url.split(bucketUrl)[1]
  2171. console.log('aws-name:', name)
  2172. if (!name) {
  2173. reject(new Error('Could not extract file name from URL'))
  2174. return
  2175. }
  2176. const params = {
  2177. Bucket: 'ccrb',
  2178. Key: name,
  2179. }
  2180. s3.getObject(params, (err: any, data: any) => {
  2181. if (err) {
  2182. console.error('S3 getObject error:', err, err.stack)
  2183. reject(err)
  2184. }
  2185. else {
  2186. console.log('S3 getObject success:', data)
  2187. resolve({ data: data.Body })
  2188. }
  2189. })
  2190. })
  2191. }
  2192. const getFile2 = (url: string): Promise<{ data: any }> => {
  2193. return new Promise((resolve, reject) => {
  2194. console.log('直接使用原始 URL 获取文件:', url)
  2195. // 直接使用 fetch 获取文件,浏览器会自动处理 URL 解码
  2196. fetch(url)
  2197. .then(response => {
  2198. if (!response.ok) {
  2199. console.error('HTTP 错误:', response.status, response.statusText)
  2200. throw new Error(`HTTP error! status: ${response.status}`)
  2201. }
  2202. console.log('文件获取成功,大小:', response.headers.get('content-length'))
  2203. return response.arrayBuffer()
  2204. })
  2205. .then(buffer => {
  2206. console.log('文件内容读取成功,大小:', buffer.byteLength)
  2207. resolve({ data: buffer })
  2208. })
  2209. .catch(error => {
  2210. console.error('Fetch error:', error)
  2211. reject(error)
  2212. })
  2213. })
  2214. }
  2215. return {
  2216. importSpecificFile,
  2217. importJSON,
  2218. importPPTXFile,
  2219. readJSON,
  2220. exportJSON2,
  2221. exporting,
  2222. imgExporting,
  2223. getFile,
  2224. getFile2,
  2225. dataToFile,
  2226. uploadFileToS3
  2227. }
  2228. }