useImport.ts 86 KB

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