useImport.ts 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450
  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 p = doc.querySelector('p')
  49. // 4. 读取 style 属性(内联样式字符串)
  50. const styleAttr = p?.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 // new (data: ArrayBuffer) => { render(settings: any): SVGElement }
  754. ): Promise<Blob> {
  755. // 1. 创建 Renderer 实例
  756. const renderer = new RendererClass(arrayBuffer)
  757. // 2. 先尝试获取图片的真实尺寸(通过临时渲染并解析 SVG 的 viewBox)
  758. let width = 800, height = 600 // 默认值
  759. try {
  760. // 使用一个较大的临时尺寸进行第一次渲染,以获取 SVG 的 viewBox
  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. }
  777. else {
  778. // 尝试从 width/height 属性获取
  779. const svgWidth = tempSvg.getAttribute('width')
  780. const svgHeight = tempSvg.getAttribute('height')
  781. if (svgWidth && svgHeight) {
  782. width = parseFloat(svgWidth)
  783. height = parseFloat(svgHeight)
  784. }
  785. }
  786. }
  787. catch (e) {
  788. console.warn('Failed to get dimensions from SVG, using default', e)
  789. }
  790. // 3. 使用实际尺寸重新渲染
  791. const settings = {
  792. width: width + 'px',
  793. height: height + 'px',
  794. xExt: width,
  795. yExt: height,
  796. mapMode: 8, // 保持宽高比
  797. }
  798. const svg = renderer.render(settings)
  799. // 4. 将 SVG 转为 data URL 并用 Image 加载
  800. const serializer = new XMLSerializer()
  801. let svgString = serializer.serializeToString(svg)
  802. // 确保有命名空间
  803. if (!svgString.includes('xmlns="http://www.w3.org/2000/svg"')) {
  804. svgString = svgString.replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"')
  805. }
  806. const blob = new Blob([svgString], { type: 'image/svg+xml' })
  807. const url = URL.createObjectURL(blob)
  808. try {
  809. const img = await new Promise<HTMLImageElement>((resolve, reject) => {
  810. const image = new Image()
  811. image.onload = () => resolve(image)
  812. image.onerror = reject
  813. image.src = url
  814. })
  815. // 5. 绘制到 canvas
  816. const canvas = document.createElement('canvas')
  817. canvas.width = img.width
  818. canvas.height = img.height
  819. const ctx = canvas.getContext('2d')!
  820. ctx.drawImage(img, 0, 0)
  821. return new Promise((resolve, reject) => {
  822. canvas.toBlob(blob => (blob ? resolve(blob) : reject(new Error('Metafile to PNG failed'))), 'image/png')
  823. })
  824. }
  825. finally {
  826. URL.revokeObjectURL(url)
  827. }
  828. }
  829. // EMF 转 PNG(使用 EMFJS.Renderer)
  830. async function convertEmfToPng(blob: Blob): Promise<Blob> {
  831. const arrayBuffer = await blob.arrayBuffer()
  832. return convertMetafileToPng(arrayBuffer, EMFJS.Renderer)
  833. }
  834. // WMF 转 PNG(使用 WMFJS.Renderer)
  835. async function convertWmfToPng(blob: Blob): Promise<Blob> {
  836. const arrayBuffer = await blob.arrayBuffer()
  837. return convertMetafileToPng(arrayBuffer, WMFJS.Renderer)
  838. }
  839. function hasTransparency(img: HTMLImageElement, ctx: CanvasRenderingContext2D): boolean {
  840. const imageData = ctx.getImageData(0, 0, img.width, img.height)
  841. const data = imageData.data
  842. // 遍历 Alpha 通道(索引 3)
  843. for (let i = 3; i < data.length; i += 4) {
  844. if (data[i] < 255) {
  845. return true // 发现任意一个像素不是完全不透明
  846. }
  847. }
  848. return false
  849. }
  850. // 对 PNG 执行白色变透明
  851. async function makeWhiteTransparentFromPng(pngBlob: Blob, tolerance: number): Promise<Blob> {
  852. const url = URL.createObjectURL(pngBlob)
  853. try {
  854. const img = await new Promise<HTMLImageElement>((resolve, reject) => {
  855. const image = new Image()
  856. image.onload = () => resolve(image)
  857. image.onerror = reject
  858. image.src = url
  859. })
  860. const canvas = document.createElement('canvas')
  861. canvas.width = img.width
  862. canvas.height = img.height
  863. const ctx = canvas.getContext('2d')!
  864. ctx.drawImage(img, 0, 0)
  865. const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
  866. const data = imageData.data
  867. for (let i = 0; i < data.length; i += 4) {
  868. const r = data[i]
  869. const g = data[i + 1]
  870. const b = data[i + 2]
  871. const dr = r - 255
  872. const dg = g - 255
  873. const db = b - 255
  874. if (Math.sqrt(dr * dr + dg * dg + db * db) <= tolerance) {
  875. data[i + 3] = 0
  876. }
  877. }
  878. ctx.putImageData(imageData, 0, 0)
  879. return new Promise((resolve, reject) => {
  880. canvas.toBlob(blob => (blob ? resolve(blob) : reject(new Error('Canvas toBlob failed'))), 'image/png')
  881. })
  882. }
  883. finally {
  884. URL.revokeObjectURL(url)
  885. }
  886. }
  887. /**
  888. * 上传 File 到 S3,返回公开访问的 URL
  889. */
  890. const uploadFileToS3 = (file: File): Promise<string> => {
  891. return new Promise((resolve, reject) => {
  892. if (typeof window === 'undefined' || !window.AWS) {
  893. reject(new Error('AWS SDK not available'))
  894. return
  895. }
  896. const credentials = {
  897. accessKeyId: 'AKIATLPEDU37QV5CHLMH',
  898. secretAccessKey: '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',
  899. }
  900. window.AWS.config.update(credentials)
  901. window.AWS.config.region = 'cn-northwest-1'
  902. const bucket = new window.AWS.S3({
  903. params: { Bucket: 'ccrb' }, httpOptions: {
  904. timeout: 600000 // 10分钟超时
  905. }
  906. })
  907. const ext = file.name.split('.').pop() || 'bin'
  908. const key = `${file.name.split('.')[0]}_${Date.now()}.${ext}`
  909. const params = {
  910. Key: 'pptto/' + key,
  911. ContentType: file.type,
  912. Body: file,
  913. ACL: 'public-read',
  914. }
  915. const options = {
  916. partSize: 5 * 1024 * 1024, // 2GB 分片,可酌情调小
  917. queueSize: 2,
  918. leavePartsOnError: true,
  919. }
  920. bucket
  921. .upload(params, options)
  922. .promise()
  923. .then(data => resolve(data.Location))
  924. .catch(err => reject(err))
  925. })
  926. }
  927. /*
  928. // 导入PPTX文件
  929. const importPPTXFile = (files: FileList, options?: { cover?: boolean; fixedViewport?: boolean; signal?: AbortSignal }) => {
  930. console.log('导入', files)
  931. const defaultOptions = {
  932. cover: false,
  933. fixedViewport: false,
  934. }
  935. const { cover, fixedViewport, signal } = { ...defaultOptions, ...options }
  936. const file = files[0]
  937. if (!file) return
  938. exporting.value = true
  939. const shapeList: ShapePoolItem[] = []
  940. for (const item of SHAPE_LIST) {
  941. shapeList.push(...item.children)
  942. }
  943. const reader = new FileReader()
  944. reader.onload = async (e: ProgressEvent<FileReader>) => {
  945. // 检查是否已取消
  946. if (signal?.aborted) {
  947. exporting.value = false
  948. return
  949. }
  950. let json = null
  951. try {
  952. json = await parse(e.target!.result as ArrayBuffer)
  953. }
  954. catch (error) {
  955. exporting.value = false
  956. console.log('导入PPTX文件失败:', error)
  957. message.error('无法正确读取 / 解析该文件')
  958. return
  959. }
  960. let ratio = 96 / 72;
  961. //let ratio = 1
  962. const width = json.size.width
  963. if (fixedViewport) ratio = 1000 / width
  964. else slidesStore.setViewportSize(width * ratio)
  965. slidesStore.setTheme({ themeColors: json.themeColors })
  966. const slides: Slide[] = []
  967. for (const item of json.slides) {
  968. const { type, value } = item.fill
  969. let background: SlideBackground
  970. if (type === 'image') {
  971. background = {
  972. type: 'image',
  973. image: {
  974. src: value.picBase64,
  975. size: 'cover',
  976. },
  977. }
  978. }
  979. else if (type === 'gradient') {
  980. background = {
  981. type: 'gradient',
  982. gradient: {
  983. type: value.path === 'line' ? 'linear' : 'radial',
  984. colors: value.colors.map(item => ({
  985. ...item,
  986. pos: parseInt(item.pos),
  987. })),
  988. rotate: value.rot + 90,
  989. },
  990. }
  991. }
  992. else {
  993. background = {
  994. type: 'solid',
  995. color: value || '#fff',
  996. }
  997. }
  998. const slide: Slide = {
  999. id: nanoid(10),
  1000. elements: [],
  1001. background,
  1002. remark: item.note || '',
  1003. }
  1004. const parseElements = (elements: Element[]) => {
  1005. const sortedElements = elements.sort((a, b) => a.order - b.order)
  1006. console.log(sortedElements)
  1007. for (const el of sortedElements) {
  1008. const originWidth = el.width || 1
  1009. const originHeight = el.height || 1
  1010. const originLeft = el.left
  1011. const originTop = el.top
  1012. el.width = el.width * ratio
  1013. el.height = el.height * ratio
  1014. el.left = el.left * ratio
  1015. el.top = el.top * ratio
  1016. if (el.type === 'text') {
  1017. const textEl: PPTTextElement = {
  1018. type: 'text',
  1019. id: nanoid(10),
  1020. width: el.width,
  1021. height: el.height,
  1022. left: el.left,
  1023. top: el.top,
  1024. rotate: el.rotate,
  1025. defaultFontName: theme.value.fontName,
  1026. defaultColor: theme.value.fontColor,
  1027. content: convertFontSizePtToPx(el.content, ratio),
  1028. lineHeight: 1,
  1029. outline: {
  1030. color: el.borderColor,
  1031. width: +(el.borderWidth * ratio).toFixed(2),
  1032. style: el.borderType,
  1033. },
  1034. fill: el.fill.type === 'color' ? el.fill.value : '',
  1035. vertical: el.isVertical,
  1036. }
  1037. if (el.shadow) {
  1038. textEl.shadow = {
  1039. h: el.shadow.h * ratio,
  1040. v: el.shadow.v * ratio,
  1041. blur: el.shadow.blur * ratio,
  1042. color: el.shadow.color,
  1043. }
  1044. }
  1045. slide.elements.push(textEl)
  1046. }
  1047. else if (el.type === 'image') {
  1048. const element: PPTImageElement = {
  1049. type: 'image',
  1050. id: nanoid(10),
  1051. src: el.src,
  1052. width: el.width,
  1053. height: el.height,
  1054. left: el.left,
  1055. top: el.top,
  1056. fixedRatio: true,
  1057. rotate: el.rotate,
  1058. flipH: el.isFlipH,
  1059. flipV: el.isFlipV,
  1060. }
  1061. if (el.borderWidth) {
  1062. element.outline = {
  1063. color: el.borderColor,
  1064. width: +(el.borderWidth * ratio).toFixed(2),
  1065. style: el.borderType,
  1066. }
  1067. }
  1068. const clipShapeTypes = ['roundRect', 'ellipse', 'triangle', 'rhombus', 'pentagon', 'hexagon', 'heptagon', 'octagon', 'parallelogram', 'trapezoid']
  1069. if (el.rect) {
  1070. element.clip = {
  1071. shape: (el.geom && clipShapeTypes.includes(el.geom)) ? el.geom : 'rect',
  1072. range: [
  1073. [
  1074. el.rect.l || 0,
  1075. el.rect.t || 0,
  1076. ],
  1077. [
  1078. 100 - (el.rect.r || 0),
  1079. 100 - (el.rect.b || 0),
  1080. ],
  1081. ]
  1082. }
  1083. }
  1084. else if (el.geom && clipShapeTypes.includes(el.geom)) {
  1085. element.clip = {
  1086. shape: el.geom,
  1087. range: [[0, 0], [100, 100]]
  1088. }
  1089. }
  1090. slide.elements.push(element)
  1091. }
  1092. else if (el.type === 'math') {
  1093. slide.elements.push({
  1094. type: 'image',
  1095. id: nanoid(10),
  1096. src: el.picBase64,
  1097. width: el.width,
  1098. height: el.height,
  1099. left: el.left,
  1100. top: el.top,
  1101. fixedRatio: true,
  1102. rotate: 0,
  1103. })
  1104. }
  1105. else if (el.type === 'audio') {
  1106. slide.elements.push({
  1107. type: 'audio',
  1108. id: nanoid(10),
  1109. src: el.blob,
  1110. width: el.width,
  1111. height: el.height,
  1112. left: el.left,
  1113. top: el.top,
  1114. rotate: 0,
  1115. fixedRatio: false,
  1116. color: theme.value.themeColors[0],
  1117. loop: false,
  1118. autoplay: false,
  1119. })
  1120. }
  1121. else if (el.type === 'video') {
  1122. slide.elements.push({
  1123. type: 'video',
  1124. id: nanoid(10),
  1125. src: (el.blob || el.src)!,
  1126. width: el.width,
  1127. height: el.height,
  1128. left: el.left,
  1129. top: el.top,
  1130. rotate: 0,
  1131. autoplay: false,
  1132. })
  1133. }
  1134. else if (el.type === 'shape') {
  1135. if (el.shapType === 'line' || /Connector/.test(el.shapType)) {
  1136. const lineElement = parseLineElement(el, ratio)
  1137. slide.elements.push(lineElement)
  1138. }
  1139. else {
  1140. const shape = shapeList.find(item => item.pptxShapeType === el.shapType)
  1141. const vAlignMap: { [key: string]: ShapeTextAlign } = {
  1142. 'mid': 'middle',
  1143. 'down': 'bottom',
  1144. 'up': 'top',
  1145. }
  1146. const gradient: Gradient | undefined = el.fill?.type === 'gradient' ? {
  1147. type: el.fill.value.path === 'line' ? 'linear' : 'radial',
  1148. colors: el.fill.value.colors.map(item => ({
  1149. ...item,
  1150. pos: parseInt(item.pos),
  1151. })),
  1152. rotate: el.fill.value.rot,
  1153. } : undefined
  1154. const pattern: string | undefined = el.fill?.type === 'image' ? el.fill.value.picBase64 : undefined
  1155. const fill = el.fill?.type === 'color' ? el.fill.value : ''
  1156. const element: PPTShapeElement = {
  1157. type: 'shape',
  1158. id: nanoid(10),
  1159. width: el.width,
  1160. height: el.height,
  1161. left: el.left,
  1162. top: el.top,
  1163. viewBox: [200, 200],
  1164. path: 'M 0 0 L 200 0 L 200 200 L 0 200 Z',
  1165. fill,
  1166. gradient,
  1167. pattern,
  1168. fixedRatio: false,
  1169. rotate: el.rotate,
  1170. outline: {
  1171. color: el.borderColor,
  1172. width: +(el.borderWidth * ratio).toFixed(2),
  1173. style: el.borderType,
  1174. },
  1175. text: {
  1176. content: convertFontSizePtToPx(el.content, ratio),
  1177. defaultFontName: theme.value.fontName,
  1178. defaultColor: theme.value.fontColor,
  1179. align: vAlignMap[el.vAlign] || 'middle',
  1180. },
  1181. flipH: el.isFlipH,
  1182. flipV: el.isFlipV,
  1183. }
  1184. if (el.shadow) {
  1185. element.shadow = {
  1186. h: el.shadow.h * ratio,
  1187. v: el.shadow.v * ratio,
  1188. blur: el.shadow.blur * ratio,
  1189. color: el.shadow.color,
  1190. }
  1191. }
  1192. if (shape) {
  1193. element.path = shape.path
  1194. element.viewBox = shape.viewBox
  1195. if (shape.pathFormula) {
  1196. element.pathFormula = shape.pathFormula
  1197. element.viewBox = [el.width, el.height]
  1198. const pathFormula = SHAPE_PATH_FORMULAS[shape.pathFormula]
  1199. if ('editable' in pathFormula && pathFormula.editable) {
  1200. element.path = pathFormula.formula(el.width, el.height, pathFormula.defaultValue)
  1201. element.keypoints = pathFormula.defaultValue
  1202. }
  1203. else element.path = pathFormula.formula(el.width, el.height)
  1204. }
  1205. }
  1206. else if (el.path && el.path.indexOf('NaN') === -1) {
  1207. const { maxX, maxY } = getSvgPathRange(el.path)
  1208. element.path = el.path
  1209. element.viewBox = [maxX || originWidth, maxY || originHeight]
  1210. }
  1211. if (el.shapType === 'custom') {
  1212. if (el.path!.indexOf('NaN') !== -1) {
  1213. if (element.width === 0) element.width = 0.1
  1214. if (element.height === 0) element.height = 0.1
  1215. element.path = el.path!.replace(/NaN/g, '0')
  1216. }
  1217. else {
  1218. element.special = true
  1219. element.path = el.path!
  1220. }
  1221. const { maxX, maxY } = getSvgPathRange(element.path)
  1222. element.viewBox = [maxX || originWidth, maxY || originHeight]
  1223. }
  1224. if (element.path) slide.elements.push(element)
  1225. }
  1226. }
  1227. else if (el.type === 'table') {
  1228. const row = el.data.length
  1229. const col = el.data[0].length
  1230. const style: TableCellStyle = {
  1231. fontname: theme.value.fontName,
  1232. color: theme.value.fontColor,
  1233. }
  1234. const data: TableCell[][] = []
  1235. for (let i = 0; i < row; i++) {
  1236. const rowCells: TableCell[] = []
  1237. for (let j = 0; j < col; j++) {
  1238. const cellData = el.data[i][j]
  1239. let textDiv: HTMLDivElement | null = document.createElement('div')
  1240. textDiv.innerHTML = cellData.text
  1241. const p = textDiv.querySelector('p')
  1242. const align = p?.style.textAlign || 'left'
  1243. const span = textDiv.querySelector('span')
  1244. const fontsize = span?.style.fontSize ? (parseInt(span?.style.fontSize) * ratio).toFixed(1) + 'px' : ''
  1245. const fontname = span?.style.fontFamily || ''
  1246. const color = span?.style.color || cellData.fontColor
  1247. rowCells.push({
  1248. id: nanoid(10),
  1249. colspan: cellData.colSpan || 1,
  1250. rowspan: cellData.rowSpan || 1,
  1251. text: textDiv.innerText,
  1252. style: {
  1253. ...style,
  1254. align: ['left', 'right', 'center'].includes(align) ? (align as 'left' | 'right' | 'center') : 'left',
  1255. fontsize,
  1256. fontname,
  1257. color,
  1258. bold: cellData.fontBold,
  1259. backcolor: cellData.fillColor,
  1260. },
  1261. })
  1262. textDiv = null
  1263. }
  1264. data.push(rowCells)
  1265. }
  1266. const allWidth = el.colWidths.reduce((a, b) => a + b, 0)
  1267. const colWidths: number[] = el.colWidths.map(item => item / allWidth)
  1268. const firstCell = el.data[0][0]
  1269. const border = firstCell.borders.top ||
  1270. firstCell.borders.bottom ||
  1271. el.borders.top ||
  1272. el.borders.bottom ||
  1273. firstCell.borders.left ||
  1274. firstCell.borders.right ||
  1275. el.borders.left ||
  1276. el.borders.right
  1277. const borderWidth = border?.borderWidth || 0
  1278. const borderStyle = border?.borderType || 'solid'
  1279. const borderColor = border?.borderColor || '#eeece1'
  1280. slide.elements.push({
  1281. type: 'table',
  1282. id: nanoid(10),
  1283. width: el.width,
  1284. height: el.height,
  1285. left: el.left,
  1286. top: el.top,
  1287. colWidths,
  1288. rotate: 0,
  1289. data,
  1290. outline: {
  1291. width: +(borderWidth * ratio || 2).toFixed(2),
  1292. style: borderStyle,
  1293. color: borderColor,
  1294. },
  1295. cellMinHeight: el.rowHeights[0] ? el.rowHeights[0] * ratio : 36,
  1296. })
  1297. }
  1298. else if (el.type === 'chart') {
  1299. let labels: string[]
  1300. let legends: string[]
  1301. let series: number[][]
  1302. if (el.chartType === 'scatterChart' || el.chartType === 'bubbleChart') {
  1303. labels = el.data[0].map((item, index) => `坐标${index + 1}`)
  1304. legends = ['X', 'Y']
  1305. series = el.data
  1306. }
  1307. else {
  1308. const data = el.data as ChartItem[]
  1309. labels = Object.values(data[0].xlabels)
  1310. legends = data.map(item => item.key)
  1311. series = data.map(item => item.values.map(v => v.y))
  1312. }
  1313. const options: ChartOptions = {}
  1314. let chartType: ChartType = 'bar'
  1315. switch (el.chartType) {
  1316. case 'barChart':
  1317. case 'bar3DChart':
  1318. chartType = 'bar'
  1319. if (el.barDir === 'bar') chartType = 'column'
  1320. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1321. break
  1322. case 'lineChart':
  1323. case 'line3DChart':
  1324. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1325. chartType = 'line'
  1326. break
  1327. case 'areaChart':
  1328. case 'area3DChart':
  1329. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1330. chartType = 'area'
  1331. break
  1332. case 'scatterChart':
  1333. case 'bubbleChart':
  1334. chartType = 'scatter'
  1335. break
  1336. case 'pieChart':
  1337. case 'pie3DChart':
  1338. chartType = 'pie'
  1339. break
  1340. case 'radarChart':
  1341. chartType = 'radar'
  1342. break
  1343. case 'doughnutChart':
  1344. chartType = 'ring'
  1345. break
  1346. default:
  1347. }
  1348. slide.elements.push({
  1349. type: 'chart',
  1350. id: nanoid(10),
  1351. chartType: chartType,
  1352. width: el.width,
  1353. height: el.height,
  1354. left: el.left,
  1355. top: el.top,
  1356. rotate: 0,
  1357. themeColors: el.colors.length ? el.colors : theme.value.themeColors,
  1358. textColor: theme.value.fontColor,
  1359. data: {
  1360. labels,
  1361. legends,
  1362. series,
  1363. },
  1364. options,
  1365. })
  1366. }
  1367. else if (el.type === 'group') {
  1368. let elements: BaseElement[] = el.elements.map(_el => {
  1369. let left = _el.left + originLeft
  1370. let top = _el.top + originTop
  1371. if (el.rotate) {
  1372. const { x, y } = calculateRotatedPosition(originLeft, originTop, originWidth, originHeight, _el.left, _el.top, el.rotate)
  1373. left = x
  1374. top = y
  1375. }
  1376. const element = {
  1377. ..._el,
  1378. left,
  1379. top,
  1380. }
  1381. if (el.isFlipH && 'isFlipH' in element) element.isFlipH = true
  1382. if (el.isFlipV && 'isFlipV' in element) element.isFlipV = true
  1383. return element
  1384. })
  1385. if (el.isFlipH) elements = flipGroupElements(elements, 'y')
  1386. if (el.isFlipV) elements = flipGroupElements(elements, 'x')
  1387. parseElements(elements)
  1388. }
  1389. else if (el.type === 'diagram') {
  1390. const elements = el.elements.map(_el => ({
  1391. ..._el,
  1392. left: _el.left + originLeft,
  1393. top: _el.top + originTop,
  1394. }))
  1395. parseElements(elements)
  1396. }
  1397. }
  1398. }
  1399. parseElements([...item.elements, ...item.layoutElements])
  1400. slides.push(slide)
  1401. }
  1402. if (cover) {
  1403. slidesStore.updateSlideIndex(0)
  1404. slidesStore.setSlides(slides)
  1405. addHistorySnapshot()
  1406. }
  1407. else if (isEmptySlide.value) {
  1408. slidesStore.setSlides(slides)
  1409. addHistorySnapshot()
  1410. }
  1411. else addSlidesFromData(slides)
  1412. exporting.value = false
  1413. }
  1414. reader.readAsArrayBuffer(file)
  1415. // 监听取消信号
  1416. signal?.addEventListener('abort', () => {
  1417. reader.abort()
  1418. exporting.value = false
  1419. })
  1420. // 监听取消信号
  1421. signal?.addEventListener('abort', () => {
  1422. reader.abort()
  1423. exporting.value = false
  1424. })
  1425. }
  1426. */
  1427. const importPPTXFile = (files: FileList, options?: { cover?: boolean; fixedViewport?: boolean; signal?: AbortSignal, onclose?: () => void }) => {
  1428. console.log('导入', files)
  1429. const defaultOptions = {
  1430. cover: false,
  1431. fixedViewport: false,
  1432. }
  1433. const { cover, fixedViewport, signal, onclose } = { ...defaultOptions, ...options }
  1434. let isNone = false
  1435. if (slides.value.length === 1 && slides.value[0].elements.length === 0) {
  1436. isNone = true
  1437. }
  1438. const file = files[0]
  1439. if (!file) return
  1440. exporting.value = true // 假设 exporting 是一个全局 ref
  1441. imgExporting.value = true // 假设 imgExporting 是一个全局 ref
  1442. // 预加载形状库(用于后续形状匹配)
  1443. const shapeList: ShapePoolItem[] = []
  1444. for (const item of SHAPE_LIST) {
  1445. shapeList.push(...item.children)
  1446. }
  1447. const reader = new FileReader()
  1448. reader.onload = async (e: ProgressEvent<FileReader>) => {
  1449. // 检查是否已取消
  1450. if (signal?.aborted) {
  1451. exporting.value = false
  1452. imgExporting.value = false
  1453. return
  1454. }
  1455. let json = null
  1456. try {
  1457. json = await parse(e.target!.result as ArrayBuffer)
  1458. }
  1459. catch (error) {
  1460. exporting.value = false
  1461. imgExporting.value = false
  1462. console.log('导入PPTX文件失败:', error)
  1463. message.error(lang.ssFileReadFail)
  1464. return
  1465. }
  1466. if (signal?.aborted) {
  1467. exporting.value = false
  1468. imgExporting.value = false
  1469. return
  1470. }
  1471. // 计算缩放比例
  1472. let ratio = 96 / 72 // PPTX 默认 72 DPI,屏幕 96 DPI
  1473. const width = json.size.width
  1474. const height = json.size.height
  1475. const viewportRatio = json.size.viewportRatio || (height && width ? height / width : undefined)
  1476. if (fixedViewport) {
  1477. ratio = 1000 / width // 固定视口宽度为 1000px
  1478. }
  1479. else {
  1480. const targetViewportSize = width * ratio
  1481. if (isNone || targetViewportSize > slidesStore.viewportSize) {
  1482. slidesStore.setViewportSize(targetViewportSize) // 调整画布大小
  1483. }
  1484. }
  1485. // 设置主题色
  1486. slidesStore.setTheme({ themeColors: json.themeColors })
  1487. const slides: Slide[] = []
  1488. // 收集当前幻灯片内所有上传任务
  1489. const uploadTasks: Promise<void>[] = []
  1490. // 遍历每一张幻灯片
  1491. for (const item of json.slides) {
  1492. // ----- 解析背景 -----
  1493. const { type, value } = item.fill
  1494. let background: SlideBackground
  1495. if (type === 'image') {
  1496. // 背景图片也可能需要上传(但 PPTX 背景图通常是内嵌 base64)
  1497. // 这里为了简化,暂不处理背景图片上传,如有需要可类似元素上传
  1498. background = {
  1499. type: 'image',
  1500. image: {
  1501. src: value.picBase64,
  1502. size: 'cover',
  1503. },
  1504. }
  1505. }
  1506. else if (type === 'gradient') {
  1507. background = {
  1508. type: 'gradient',
  1509. gradient: {
  1510. type: value.path === 'line' ? 'linear' : 'radial',
  1511. colors: value.colors.map(item => ({
  1512. ...item,
  1513. pos: parseInt(item.pos),
  1514. })),
  1515. rotate: value.rot + 90,
  1516. },
  1517. }
  1518. }
  1519. else {
  1520. background = {
  1521. type: 'solid',
  1522. color: value || '#fff',
  1523. }
  1524. }
  1525. const slide: Slide = {
  1526. id: nanoid(10),
  1527. elements: [],
  1528. background,
  1529. remark: item.note || '',
  1530. }
  1531. // ----- 解析元素(递归函数)-----
  1532. const parseElements = async (elements: any[], pelements: any = null) => {
  1533. // 按绘制顺序排序
  1534. const sortedElements = elements.sort((a, b) => a.order - b.order)
  1535. console.log(sortedElements)
  1536. for (const el of sortedElements) {
  1537. // 保存原始尺寸用于后续可能的路径计算
  1538. const originWidth = el.width || 1
  1539. const originHeight = el.height || 1
  1540. const originLeft = el.left
  1541. const originTop = el.top
  1542. // 保存原始尺寸用于后续可能的路径计算
  1543. const poriginWidth = pelements?.width
  1544. const poriginHeight = pelements?.height
  1545. const poriginLeft = pelements?.left
  1546. const poriginTop = pelements?.top
  1547. // 应用缩放
  1548. el.width = el.width * ratio
  1549. el.height = el.height * ratio
  1550. el.left = el.left * ratio
  1551. el.top = el.top * ratio
  1552. if (el.type === 'text') {
  1553. const vAlignMap: { [key: string]: ShapeTextAlign } = {
  1554. mid: 'middle',
  1555. down: 'bottom',
  1556. up: 'top',
  1557. }
  1558. const textEl: PPTTextElement = {
  1559. type: 'text',
  1560. id: nanoid(10),
  1561. width: el.width,
  1562. height: el.height,
  1563. left: el.left,
  1564. top: el.top,
  1565. rotate: el.rotate,
  1566. defaultFontName: theme.value.fontName,
  1567. defaultColor: theme.value.fontColor,
  1568. content: convertFontSizePtToPx(el.content, ratio, el.autoFit),
  1569. style: getStyle(convertFontSizePtToPx(el.content, ratio, el.autoFit)),
  1570. lineHeight: 1.5,
  1571. align: vAlignMap[el.vAlign] || 'middle',
  1572. outline: {
  1573. color: el.borderColor,
  1574. width: +(el.borderWidth * ratio).toFixed(2),
  1575. style: el.borderType,
  1576. },
  1577. fill: el.fill.type === 'color' ? el.fill.value : '',
  1578. vertical: el.isVertical,
  1579. }
  1580. if (el.shadow) {
  1581. textEl.shadow = {
  1582. h: el.shadow.h * ratio,
  1583. v: el.shadow.v * ratio,
  1584. blur: el.shadow.blur * ratio,
  1585. color: el.shadow.color,
  1586. }
  1587. }
  1588. slide.elements.push(textEl)
  1589. }
  1590. // ---------- 图片 ----------
  1591. if (el.type === 'image') {
  1592. const element: PPTImageElement = {
  1593. type: 'image',
  1594. id: nanoid(10),
  1595. src: el.src, // 可能是 base64 或已有 URL
  1596. width: el.width,
  1597. height: el.height,
  1598. left: el.left,
  1599. top: el.top,
  1600. fixedRatio: true,
  1601. rotate: el.rotate,
  1602. flipH: el.isFlipH,
  1603. flipV: el.isFlipV,
  1604. }
  1605. // 边框
  1606. if (el.borderWidth) {
  1607. element.outline = {
  1608. color: el.borderColor,
  1609. width: +(el.borderWidth * ratio).toFixed(2),
  1610. style: el.borderType,
  1611. }
  1612. }
  1613. // 裁剪(形状剪裁)
  1614. const clipShapeTypes = ['roundRect', 'ellipse', 'triangle', 'rhombus', 'pentagon', 'hexagon', 'heptagon', 'octagon', 'parallelogram', 'trapezoid']
  1615. if (el.rect) {
  1616. element.clip = {
  1617. shape: (el.geom && clipShapeTypes.includes(el.geom)) ? el.geom : 'rect',
  1618. range: [
  1619. [el.rect.l || 0, el.rect.t || 0],
  1620. [100 - (el.rect.r || 0), 100 - (el.rect.b || 0)],
  1621. ],
  1622. }
  1623. }
  1624. else if (el.geom && clipShapeTypes.includes(el.geom)) {
  1625. element.clip = {
  1626. shape: el.geom,
  1627. range: [[0, 0], [100, 100]],
  1628. }
  1629. }
  1630. // 如果 src 是 base64,触发上传
  1631. if (el.src && typeof el.src === 'string' && el.src.startsWith('blob:')) {
  1632. const uploadTask = (async () => {
  1633. try {
  1634. const file = await makeWhiteTransparent(el.src, `image_${Date.now()}.png`)
  1635. if (file) {
  1636. const url = await uploadFileToS3(file)
  1637. element.src = url // 替换为远程 URL
  1638. const slidesStore = useSlidesStore()
  1639. slidesStore.updateElement({ id: element.id, props: { src: url } })
  1640. }
  1641. }
  1642. catch (error) {
  1643. console.error('Image upload failed:', error)
  1644. // 失败时保留原 base64(或可置空)
  1645. }
  1646. })()
  1647. uploadTasks.push(uploadTask)
  1648. }
  1649. slide.elements.push(element)
  1650. }
  1651. else if (el.type === 'math') {
  1652. const element: PPTImageElement = {
  1653. type: 'image',
  1654. id: nanoid(10),
  1655. src: el.picBase64,
  1656. width: el.width,
  1657. height: el.height,
  1658. left: el.left,
  1659. top: el.top,
  1660. fixedRatio: true,
  1661. rotate: 0,
  1662. }
  1663. // 如果 src 是 base64,触发上传
  1664. if (el.picBase64 && typeof el.picBase64 === 'string' && el.picBase64.startsWith('blob:')) {
  1665. const uploadTask = (async () => {
  1666. try {
  1667. const file = makeWhiteTransparent(el.picBase64, `image_${Date.now()}.png`)
  1668. if (file) {
  1669. const url = await uploadFileToS3(file)
  1670. element.src = url // 替换为远程 URL
  1671. const slidesStore = useSlidesStore()
  1672. slidesStore.updateElement({ id: element.id, props: { src: url } })
  1673. }
  1674. }
  1675. catch (error) {
  1676. console.error('Image upload failed:', error)
  1677. // 失败时保留原 base64(或可置空)
  1678. }
  1679. })()
  1680. uploadTasks.push(uploadTask)
  1681. }
  1682. slide.elements.push(element)
  1683. }
  1684. // ---------- 音频 ----------
  1685. else if (el.type === 'audio') {
  1686. const element: PPTAudioElement = {
  1687. type: 'audio',
  1688. id: nanoid(10),
  1689. src: el.blob,
  1690. width: el.width,
  1691. height: el.height,
  1692. left: el.left,
  1693. top: el.top,
  1694. rotate: 0,
  1695. fixedRatio: false,
  1696. color: theme.value.themeColors[0],
  1697. loop: false,
  1698. autoplay: false,
  1699. }
  1700. const localData = el.blob || (el.src && typeof el.src === 'string' && el.src.startsWith('data:') ? el.src : null)
  1701. if (localData) {
  1702. const uploadTask = (async () => {
  1703. try {
  1704. const file = await dataToFile(localData, `audio_${Date.now()}.mp3`, 'audio/mpeg')
  1705. if (file) {
  1706. const url = await uploadFileToS3(file)
  1707. element.src = url
  1708. const slidesStore = useSlidesStore()
  1709. slidesStore.updateElement({ id: element.id, props: { src: url } })
  1710. }
  1711. }
  1712. catch (error) {
  1713. console.error('Audio upload failed:', error)
  1714. }
  1715. })()
  1716. uploadTasks.push(uploadTask)
  1717. }
  1718. slide.elements.push(element)
  1719. }
  1720. // ---------- 视频 ----------
  1721. else if (el.type === 'video') {
  1722. const element: PPTVideoElement = {
  1723. type: 'video',
  1724. id: nanoid(10),
  1725. src: (el.blob || el.src)!,
  1726. width: el.width,
  1727. height: el.height,
  1728. left: el.left,
  1729. top: el.top,
  1730. rotate: 0,
  1731. autoplay: false,
  1732. }
  1733. const localData = el.blob || (el.src && typeof el.src === 'string' && el.src.startsWith('data:') ? el.src : null)
  1734. if (localData) {
  1735. const uploadTask = (async () => {
  1736. try {
  1737. const file = await dataToFile(localData, `video_${Date.now()}.mp4`, 'video/mp4')
  1738. if (file) {
  1739. const url = await uploadFileToS3(file)
  1740. element.src = url
  1741. const slidesStore = useSlidesStore()
  1742. slidesStore.updateElement({ id: element.id, props: { src: url } })
  1743. }
  1744. }
  1745. catch (error) {
  1746. console.error('Video upload failed:', error)
  1747. }
  1748. })()
  1749. uploadTasks.push(uploadTask)
  1750. }
  1751. slide.elements.push(element)
  1752. }
  1753. // ---------- 形状 ----------
  1754. else if (el.type === 'shape') {
  1755. if (el.shapType === 'line' || /Connector/.test(el.shapType)) {
  1756. // 线条元素(单独处理)
  1757. const lineElement = parseLineElement(el, ratio)
  1758. slide.elements.push(lineElement)
  1759. }
  1760. else {
  1761. const shape = shapeList.find(item => item.pptxShapeType === el.shapType)
  1762. const vAlignMap: { [key: string]: ShapeTextAlign } = {
  1763. mid: 'middle',
  1764. down: 'bottom',
  1765. up: 'top',
  1766. }
  1767. const gradient: Gradient | undefined = el.fill?.type === 'gradient'
  1768. ? {
  1769. type: el.fill.value.path === 'line' ? 'linear' : 'radial',
  1770. colors: el.fill.value.colors.map(item => ({
  1771. ...item,
  1772. pos: parseInt(item.pos),
  1773. })),
  1774. rotate: el.fill.value.rot,
  1775. }
  1776. : undefined
  1777. const pattern: string | undefined = el.fill?.type === 'image' ? el.fill.value.picBase64 : undefined
  1778. const fill = el.fill?.type === 'color' ? el.fill.value : 'none'
  1779. const style = getStyle(convertFontSizePtToPx(el.content, ratio, el.autoFit)) + (el.pathBBox?.pWidth ? ';width:' + (el.pathBBox?.pWidth * ratio) + 'px;height:' + (el.pathBBox?.pHeight * ratio) + 'px;' : '') // 设置字体的样式等,这里由于不支持的样式在里面会过滤
  1780. const element: PPTShapeElement = {
  1781. type: 'shape',
  1782. id: nanoid(10),
  1783. width: el.width,
  1784. height: el.height,
  1785. left: el.left,
  1786. top: el.top,
  1787. viewBox: [200, 200],
  1788. path: 'M 0 0 L 200 0 L 200 200 L 0 200 Z',
  1789. fill,
  1790. gradient,
  1791. pattern,
  1792. fixedRatio: false,
  1793. rotate: el.rotate,
  1794. pathBBox: el.pathBBox,
  1795. outline: {
  1796. color: el.borderColor,
  1797. width: +(el.borderWidth * ratio).toFixed(2),
  1798. style: el.borderType,
  1799. },
  1800. text: {
  1801. content: convertFontSizePtToPx(el.content, ratio, el.autoFit),
  1802. style: style,
  1803. defaultFontName: theme.value.fontName,
  1804. defaultColor: theme.value.fontColor,
  1805. align: vAlignMap[el.vAlign] || 'middle',
  1806. },
  1807. flipH: el.isFlipH,
  1808. flipV: el.isFlipV,
  1809. }
  1810. if (el.shadow) {
  1811. element.shadow = {
  1812. h: el.shadow.h * ratio,
  1813. v: el.shadow.v * ratio,
  1814. blur: el.shadow.blur * ratio,
  1815. color: el.shadow.color,
  1816. }
  1817. }
  1818. if (shape) {
  1819. const { maxX, maxY } = getSvgPathRange(el.path)
  1820. element.path = el.path
  1821. element.viewBox = poriginWidth ? [maxX, maxY] : [originWidth, originHeight]
  1822. if (shape.pathFormula) {
  1823. element.pathFormula = shape.pathFormula
  1824. element.viewBox = [el.width, el.height]
  1825. // element.viewBox = [poriginWidth || originWidth || maxX, poriginHeight || originHeight || maxY];
  1826. const pathFormula = SHAPE_PATH_FORMULAS[shape.pathFormula]
  1827. if ('editable' in pathFormula && pathFormula.editable) {
  1828. element.path = pathFormula.formula(el.width, el.height, pathFormula.defaultValue)
  1829. element.keypoints = pathFormula.defaultValue
  1830. }
  1831. else {
  1832. element.path = pathFormula.formula(el.width, el.height)
  1833. }
  1834. }
  1835. }
  1836. else if (el.path && el.path.indexOf('NaN') === -1) {
  1837. const { maxX, maxY } = getSvgPathRange(el.path)
  1838. element.path = el.path
  1839. element.viewBox = poriginWidth ? [maxX, maxY] : [originWidth, originHeight]
  1840. // element.viewBox = [originWidth || maxX, originHeight || maxY];
  1841. // element.viewBox = originWidth? [(originWidth/(poriginWidth||1)), (originHeight/(poriginHeight||1))] : [maxX, maxY];
  1842. // element.viewBox = [poriginWidth || maxX, poriginHeight || maxY];
  1843. }
  1844. if (el.shapType === 'custom') {
  1845. if (el.path!.indexOf('NaN') !== -1) {
  1846. if (element.width === 0) element.width = 0.1
  1847. if (element.height === 0) element.height = 0.1
  1848. element.path = el.path!.replace(/NaN/g, '0')
  1849. }
  1850. const { maxX, maxY } = getSvgPathRange(element.path)
  1851. element.viewBox = poriginWidth ? [maxX, maxY] : [originWidth, originHeight]
  1852. // element.viewBox = [originWidth || maxX, originHeight || maxY];
  1853. // element.viewBox = [poriginWidth || originWidth || maxX, poriginHeight || originHeight || maxY];
  1854. // element.viewBox = [poriginWidth || originWidth || maxX, poriginHeight || originHeight || maxY];
  1855. // element.viewBox = [Math.max(maxX, originWidth), Math.max(maxY, originHeight)];
  1856. // element.viewBox = [originWidth, originHeight];
  1857. }
  1858. if (element.path) slide.elements.push(element)
  1859. }
  1860. }
  1861. // ---------- 表格 ----------
  1862. else if (el.type === 'table') {
  1863. const row = el.data.length
  1864. const col = el.data[0].length
  1865. const style: TableCellStyle = {
  1866. fontname: theme.value.fontName,
  1867. color: theme.value.fontColor,
  1868. }
  1869. const data: TableCell[][] = []
  1870. for (let i = 0; i < row; i++) {
  1871. const rowCells: TableCell[] = []
  1872. for (let j = 0; j < col; j++) {
  1873. const cellData = el.data[i][j]
  1874. let textDiv: HTMLDivElement | null = document.createElement('div')
  1875. textDiv.innerHTML = cellData.text
  1876. const p = textDiv.querySelector('p')
  1877. const align = p?.style.textAlign || 'left'
  1878. const span = textDiv.querySelector('span')
  1879. const fontsize = span?.style.fontSize
  1880. ? (parseInt(span?.style.fontSize) * ratio).toFixed(1) + 'px'
  1881. : ''
  1882. const fontname = span?.style.fontFamily || ''
  1883. const color = span?.style.color || cellData.fontColor
  1884. rowCells.push({
  1885. id: nanoid(10),
  1886. colspan: cellData.colSpan || 1,
  1887. rowspan: cellData.rowSpan || 1,
  1888. text: textDiv.innerText,
  1889. style: {
  1890. ...style,
  1891. align: ['left', 'right', 'center'].includes(align) ? (align as 'left' | 'right' | 'center') : 'left',
  1892. fontsize,
  1893. fontname,
  1894. color,
  1895. bold: cellData.fontBold,
  1896. backcolor: cellData.fillColor,
  1897. },
  1898. })
  1899. textDiv = null
  1900. }
  1901. data.push(rowCells)
  1902. }
  1903. const allWidth = el.colWidths.reduce((a, b) => a + b, 0)
  1904. const colWidths: number[] = el.colWidths.map(item => item / allWidth)
  1905. const firstCell = el.data[0][0]
  1906. const border = firstCell.borders.top ||
  1907. firstCell.borders.bottom ||
  1908. el.borders.top ||
  1909. el.borders.bottom ||
  1910. firstCell.borders.left ||
  1911. firstCell.borders.right ||
  1912. el.borders.left ||
  1913. el.borders.right
  1914. const borderWidth = border?.borderWidth || 0
  1915. const borderStyle = border?.borderType || 'solid'
  1916. const borderColor = border?.borderColor || '#eeece1'
  1917. slide.elements.push({
  1918. type: 'table',
  1919. id: nanoid(10),
  1920. width: el.width,
  1921. height: el.height,
  1922. left: el.left,
  1923. top: el.top,
  1924. colWidths,
  1925. rotate: 0,
  1926. data,
  1927. outline: {
  1928. width: +(borderWidth * ratio || 2).toFixed(2),
  1929. style: borderStyle,
  1930. color: borderColor,
  1931. },
  1932. cellMinHeight: el.rowHeights[0] ? el.rowHeights[0] * ratio : 36,
  1933. })
  1934. }
  1935. // ---------- 图表 ----------
  1936. else if (el.type === 'chart') {
  1937. let labels: string[]
  1938. let legends: string[]
  1939. let series: number[][]
  1940. if (el.chartType === 'scatterChart' || el.chartType === 'bubbleChart') {
  1941. labels = el.data[0].map((_, index) => lang.ssCoord.replace(/\*/g, (index + 1)))
  1942. legends = ['X', 'Y']
  1943. series = el.data
  1944. }
  1945. else {
  1946. const data = el.data as ChartItem[]
  1947. labels = Object.values(data[0].xlabels)
  1948. legends = data.map(item => item.key)
  1949. series = data.map(item => item.values.map(v => v.y))
  1950. }
  1951. const options: ChartOptions = {}
  1952. let chartType: ChartType = 'bar'
  1953. switch (el.chartType) {
  1954. case 'barChart':
  1955. case 'bar3DChart':
  1956. chartType = 'bar'
  1957. if (el.barDir === 'bar') chartType = 'column'
  1958. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1959. break
  1960. case 'lineChart':
  1961. case 'line3DChart':
  1962. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1963. chartType = 'line'
  1964. break
  1965. case 'areaChart':
  1966. case 'area3DChart':
  1967. if (el.grouping === 'stacked' || el.grouping === 'percentStacked') options.stack = true
  1968. chartType = 'area'
  1969. break
  1970. case 'scatterChart':
  1971. case 'bubbleChart':
  1972. chartType = 'scatter'
  1973. break
  1974. case 'pieChart':
  1975. case 'pie3DChart':
  1976. chartType = 'pie'
  1977. break
  1978. case 'radarChart':
  1979. chartType = 'radar'
  1980. break
  1981. case 'doughnutChart':
  1982. chartType = 'ring'
  1983. break
  1984. default:
  1985. }
  1986. slide.elements.push({
  1987. type: 'chart',
  1988. id: nanoid(10),
  1989. chartType,
  1990. width: el.width,
  1991. height: el.height,
  1992. left: el.left,
  1993. top: el.top,
  1994. rotate: 0,
  1995. themeColors: el.colors.length ? el.colors : theme.value.themeColors,
  1996. textColor: theme.value.fontColor,
  1997. data: {
  1998. labels,
  1999. legends,
  2000. series,
  2001. },
  2002. options,
  2003. })
  2004. }
  2005. // ---------- 组合 ----------
  2006. else if (el.type === 'group') {
  2007. // 先将子元素坐标转换到画布绝对坐标
  2008. let elements: BaseElement[] = el.elements.map((_el: any) => {
  2009. let left = _el.left + originLeft
  2010. let top = _el.top + originTop
  2011. if (el.rotate) {
  2012. const { x, y } = calculateRotatedPosition(
  2013. originLeft, originTop, originWidth, originHeight,
  2014. _el.left, _el.top, el.rotate
  2015. )
  2016. left = x
  2017. top = y
  2018. }
  2019. const element = {
  2020. ..._el,
  2021. left,
  2022. top,
  2023. }
  2024. if (el.isFlipH && 'isFlipH' in element) element.isFlipH = true
  2025. if (el.isFlipV && 'isFlipV' in element) element.isFlipV = true
  2026. return element
  2027. })
  2028. if (el.isFlipH) elements = flipGroupElements(elements, 'y')
  2029. if (el.isFlipV) elements = flipGroupElements(elements, 'x')
  2030. // 递归解析子元素(注意:子元素的上传任务会加入同一个 uploadTasks 数组)
  2031. await parseElements(elements, el)
  2032. }
  2033. // ---------- 图表组合(SmartArt)----------
  2034. else if (el.type === 'diagram') {
  2035. const elements = el.elements.map((_el: any) => ({
  2036. ..._el,
  2037. left: _el.left + originLeft,
  2038. top: _el.top + originTop,
  2039. }))
  2040. await parseElements(elements, el)
  2041. }
  2042. }
  2043. }
  2044. // 开始解析当前幻灯片的所有元素(包括布局元素)
  2045. await parseElements([...item.elements, ...item.layoutElements])
  2046. // 幻灯片构建完成,加入数组
  2047. slides.push(slide)
  2048. }
  2049. // 根据选项将幻灯片插入 store
  2050. if (cover) {
  2051. slidesStore.updateSlideIndex(0)
  2052. slidesStore.setSlides(slides)
  2053. addHistorySnapshot()
  2054. }
  2055. else if (isEmptySlide.value) {
  2056. slidesStore.setSlides(slides)
  2057. addHistorySnapshot()
  2058. }
  2059. else {
  2060. addSlidesFromData(slides)
  2061. }
  2062. // 等待当前幻灯片内所有上传任务完成
  2063. // await Promise.all(uploadTasks)
  2064. Promise.all(uploadTasks).then(() => {
  2065. imgExporting.value = false
  2066. }).catch(() => {
  2067. imgExporting.value = false
  2068. })
  2069. exporting.value = false
  2070. onclose?.()
  2071. /*
  2072. // 更新视口尺寸(如果提供了的话)
  2073. if (width !== undefined && height !== undefined) {
  2074. console.log('正在触发视口尺寸更新事件:', { width, height, viewportRatio })
  2075. // 同时也要更新slidesStore中的相关数据
  2076. if (slidesStore.setViewportSize) {
  2077. console.log('正在更新store中的视口尺寸')
  2078. slidesStore.setViewportSize(width)
  2079. if (slidesStore.setViewportRatio && viewportRatio !== undefined) {
  2080. slidesStore.setViewportRatio(viewportRatio)
  2081. console.log('视口比例已更新:', viewportRatio)
  2082. }
  2083. }
  2084. window.dispatchEvent(new CustomEvent('viewportSizeUpdated', {
  2085. detail: { width, height, viewportRatio }
  2086. }))
  2087. console.log('视口尺寸更新事件已触发')
  2088. }
  2089. // 导入成功后,触发画布尺寸更新
  2090. // 使用 nextTick 确保DOM更新完成后再触发
  2091. console.log('开始触发画布尺寸更新事件...')
  2092. nextTick(() => {
  2093. console.log('DOM更新完成,触发 slidesDataUpdated 事件')
  2094. // 触发自定义事件,通知需要更新画布尺寸的组件
  2095. window.dispatchEvent(new CustomEvent('slidesDataUpdated', {
  2096. detail: {
  2097. slides,
  2098. cover,
  2099. title,
  2100. theme,
  2101. width,
  2102. height,
  2103. viewportRatio,
  2104. timestamp: Date.now()
  2105. }
  2106. }))
  2107. console.log('slidesDataUpdated 事件已触发')
  2108. // 检查并调整幻灯片索引,确保在有效范围内
  2109. const newSlideCount = slides.length
  2110. const currentIndex = slidesStore.slideIndex
  2111. if (currentIndex >= newSlideCount) {
  2112. console.log('调整幻灯片索引:', currentIndex, '->', Math.max(0, newSlideCount - 1))
  2113. slidesStore.updateSlideIndex(Math.max(0, newSlideCount - 1))
  2114. }
  2115. console.log('画布尺寸更新事件处理完成')
  2116. })
  2117. */
  2118. }
  2119. reader.readAsArrayBuffer(file)
  2120. }
  2121. const getFile = (url: string): Promise<{ data: any }> => {
  2122. return new Promise((resolve, reject) => {
  2123. // 检查 AWS SDK 是否可用
  2124. if (typeof window !== 'undefined' && !window.AWS) {
  2125. reject(new Error('AWS SDK not available'))
  2126. return
  2127. }
  2128. const credentials = {
  2129. accessKeyId: 'AKIATLPEDU37QV5CHLMH',
  2130. secretAccessKey: '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',
  2131. } // 秘钥形式的登录上传
  2132. window.AWS.config.update(credentials)
  2133. window.AWS.config.region = 'cn-northwest-1' // 设置区域
  2134. const s3 = new window.AWS.S3({ params: { Bucket: 'ccrb' } })
  2135. // 解析文件名
  2136. const bucketUrl = 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/'
  2137. if (!url.startsWith(bucketUrl)) {
  2138. reject(new Error('Invalid S3 URL format'))
  2139. return
  2140. }
  2141. const name = decodeURIComponent(url.split(bucketUrl)[1])
  2142. // const name = url.split(bucketUrl)[1]
  2143. console.log('aws-name:', name)
  2144. if (!name) {
  2145. reject(new Error('Could not extract file name from URL'))
  2146. return
  2147. }
  2148. const params = {
  2149. Bucket: 'ccrb',
  2150. Key: name,
  2151. }
  2152. s3.getObject(params, (err: any, data: any) => {
  2153. if (err) {
  2154. console.error('S3 getObject error:', err, err.stack)
  2155. reject(err)
  2156. }
  2157. else {
  2158. console.log('S3 getObject success:', data)
  2159. resolve({ data: data.Body })
  2160. }
  2161. })
  2162. })
  2163. }
  2164. const getFile2 = (url: string): Promise<{ data: any }> => {
  2165. return new Promise((resolve, reject) => {
  2166. console.log('直接使用原始 URL 获取文件:', url)
  2167. // 直接使用 fetch 获取文件,浏览器会自动处理 URL 解码
  2168. fetch(url)
  2169. .then(response => {
  2170. if (!response.ok) {
  2171. console.error('HTTP 错误:', response.status, response.statusText)
  2172. throw new Error(`HTTP error! status: ${response.status}`)
  2173. }
  2174. console.log('文件获取成功,大小:', response.headers.get('content-length'))
  2175. return response.arrayBuffer()
  2176. })
  2177. .then(buffer => {
  2178. console.log('文件内容读取成功,大小:', buffer.byteLength)
  2179. resolve({ data: buffer })
  2180. })
  2181. .catch(error => {
  2182. console.error('Fetch error:', error)
  2183. reject(error)
  2184. })
  2185. })
  2186. }
  2187. return {
  2188. importSpecificFile,
  2189. importJSON,
  2190. importPPTXFile,
  2191. readJSON,
  2192. exportJSON2,
  2193. exporting,
  2194. imgExporting,
  2195. getFile,
  2196. getFile2,
  2197. dataToFile,
  2198. uploadFileToS3
  2199. }
  2200. }