useImport.ts 87 KB

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