office.mjs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. /**
  2. * 本地 Office / PDF 读写(零依赖)
  3. * ------------------------------------------------
  4. * 能力边界(都是实测过的,不要在这里写"看起来能"的功能):
  5. * - docx:读正文/表格文字;写标题、段落、项目符号、表格
  6. * - xlsx:读单元格值;写多表、纯文本+数字
  7. * - pptx:只读(按页提取文字);写 pptx 由 cococlass 平台负责
  8. * - pdf :提取文字(文字型 PDF);HTML → PDF 用本机 Chrome/Edge 打印
  9. *
  10. * 为什么不用 COM 驱动 WPS:COM 会执行任意本地代码,客户端安全策略默认拦截,
  11. * 与其写一段在多数机器上跑不通的脚本,不如直接改文件——老师要的是结果。
  12. */
  13. import fs from 'node:fs'
  14. import path from 'node:path'
  15. import zlib from 'node:zlib'
  16. import { execFile } from 'node:child_process'
  17. import { unzip, zip } from './zip.mjs'
  18. const XESC = (s) => String(s)
  19. .replace(/&/g, '&')
  20. .replace(/</g, '&lt;')
  21. .replace(/>/g, '&gt;')
  22. .replace(/"/g, '&quot;')
  23. const XUNESC = (s) => String(s)
  24. .replace(/&lt;/g, '<')
  25. .replace(/&gt;/g, '>')
  26. .replace(/&quot;/g, '"')
  27. .replace(/&apos;/g, "'")
  28. .replace(/&#(\d+);/g, (_m, d) => String.fromCodePoint(Number(d)))
  29. .replace(/&amp;/g, '&')
  30. /** 从 XML 里按标签取纯文字(保留段落换行)。 */
  31. function textFromXml (xml, { para = 'w:p', text = 'w:t', breakTag = 'w:br' } = {}) {
  32. const lines = []
  33. const paraRe = new RegExp(`<${para}[\\s>][\\s\\S]*?</${para}>|<${para}/>`, 'g')
  34. const blocks = xml.match(paraRe) || [xml]
  35. for (const block of blocks) {
  36. let line = ''
  37. const tokenRe = new RegExp(`<${text}(?:\\s[^>]*)?>([\\s\\S]*?)</${text}>|<${breakTag}\\s*/>|<w:tab\\s*/>`, 'g')
  38. let m
  39. while ((m = tokenRe.exec(block))) {
  40. if (m[1] !== undefined) line += XUNESC(m[1])
  41. else if (m[0].startsWith('<w:tab')) line += '\t'
  42. else line += '\n'
  43. }
  44. if (line.trim()) lines.push(line)
  45. }
  46. return lines.join('\n')
  47. }
  48. // ------------------------------------------------------------------ docx 读
  49. function readDocx (file) {
  50. const parts = unzip(fs.readFileSync(file))
  51. const doc = parts.get('word/document.xml')
  52. if (!doc) throw new Error('这个 .docx 里找不到正文(可能不是 Word 文件,或者是老式 .doc)')
  53. const xml = doc.toString('utf8')
  54. const body = textFromXml(xml)
  55. // 表格单独抽出来,老师最常问"这张表里第三列是什么"
  56. const tables = []
  57. const tblRe = /<w:tbl>[\s\S]*?<\/w:tbl>/g
  58. let t
  59. while ((t = tblRe.exec(xml))) {
  60. const rows = []
  61. const rowRe = /<w:tr[\s>][\s\S]*?<\/w:tr>/g
  62. let r
  63. while ((r = rowRe.exec(t[0]))) {
  64. const cells = []
  65. const cellRe = /<w:tc>[\s\S]*?<\/w:tc>/g
  66. let c
  67. while ((c = cellRe.exec(r[0]))) cells.push(textFromXml(c[0]).replace(/\n/g, ' ').trim())
  68. rows.push(cells)
  69. }
  70. tables.push(rows)
  71. }
  72. return { kind: 'docx', text: body, tables, chars: body.length }
  73. }
  74. // ------------------------------------------------------------------ xlsx 读
  75. function colIndex (ref) {
  76. const letters = (ref.match(/^[A-Z]+/) || ['A'])[0]
  77. let n = 0
  78. for (const ch of letters) n = n * 26 + (ch.charCodeAt(0) - 64)
  79. return n - 1
  80. }
  81. function readXlsx (file) {
  82. const parts = unzip(fs.readFileSync(file))
  83. const shared = []
  84. const sst = parts.get('xl/sharedStrings.xml')
  85. if (sst) {
  86. const re = /<si>([\s\S]*?)<\/si>/g
  87. let m
  88. while ((m = re.exec(sst.toString('utf8')))) {
  89. const texts = [...m[1].matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((x) => XUNESC(x[1]))
  90. shared.push(texts.join(''))
  91. }
  92. }
  93. // 表名 ↔ 文件:先读 workbook 的 sheet 顺序,找不到就按文件名排序
  94. const sheets = []
  95. const wb = parts.get('xl/workbook.xml')
  96. const names = wb ? [...wb.toString('utf8').matchAll(/<sheet[^>]*name="([^"]*)"/g)].map((m) => XUNESC(m[1])) : []
  97. const sheetFiles = [...parts.keys()].filter((k) => /^xl\/worksheets\/sheet\d+\.xml$/.test(k))
  98. .sort((a, b) => Number(a.match(/(\d+)\.xml$/)[1]) - Number(b.match(/(\d+)\.xml$/)[1]))
  99. for (let i = 0; i < sheetFiles.length; i++) {
  100. const xml = parts.get(sheetFiles[i]).toString('utf8')
  101. const rows = []
  102. const rowRe = /<row[^>]*>([\s\S]*?)<\/row>/g
  103. let rm
  104. while ((rm = rowRe.exec(xml))) {
  105. const cells = []
  106. const cellRe = /<c([^>]*)>([\s\S]*?)<\/c>|<c([^>]*)\/>/g
  107. let cm
  108. while ((cm = cellRe.exec(rm[1]))) {
  109. const attrs = cm[1] || cm[3] || ''
  110. const inner = cm[2] || ''
  111. const ref = (attrs.match(/r="([A-Z]+\d+)"/) || [])[1]
  112. const type = (attrs.match(/t="([^"]+)"/) || [])[1]
  113. let value = ''
  114. if (type === 'inlineStr') {
  115. value = [...inner.matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((x) => XUNESC(x[1])).join('')
  116. } else {
  117. const v = (inner.match(/<v>([\s\S]*?)<\/v>/) || [])[1]
  118. if (v !== undefined) value = type === 's' ? (shared[Number(v)] ?? '') : XUNESC(v)
  119. }
  120. const idx = ref ? colIndex(ref) : cells.length
  121. cells[idx] = value
  122. }
  123. for (let k = 0; k < cells.length; k++) if (cells[k] === undefined) cells[k] = ''
  124. if (cells.some((c) => c !== '')) rows.push(cells)
  125. }
  126. sheets.push({ name: names[i] || sheetFiles[i].replace(/^xl\/worksheets\//, ''), rows })
  127. }
  128. return { kind: 'xlsx', sheets, sheetCount: sheets.length }
  129. }
  130. // ------------------------------------------------------------------ pptx 读
  131. function readPptx (file) {
  132. const parts = unzip(fs.readFileSync(file))
  133. const files = [...parts.keys()]
  134. .filter((k) => /^ppt\/slides\/slide\d+\.xml$/.test(k))
  135. .sort((a, b) => Number(a.match(/(\d+)\.xml$/)[1]) - Number(b.match(/(\d+)\.xml$/)[1]))
  136. if (!files.length) throw new Error('这个 .pptx 里没有幻灯片(可能是 .ppt 老格式)')
  137. const slides = files.map((k, i) => {
  138. const xml = parts.get(k).toString('utf8')
  139. const paras = []
  140. for (const p of xml.match(/<a:p>[\s\S]*?<\/a:p>/g) || []) {
  141. const line = [...p.matchAll(/<a:t(?:\s[^>]*)?>([\s\S]*?)<\/a:t>/g)].map((m) => XUNESC(m[1])).join('')
  142. if (line.trim()) paras.push(line)
  143. }
  144. return { index: i + 1, texts: paras }
  145. })
  146. return { kind: 'pptx', slideCount: slides.length, slides }
  147. }
  148. // ------------------------------------------------------------------ pdf 读
  149. /*
  150. * 为什么要这么麻烦(2026-11-19 现场):
  151. * 老师从飞书下载的 PDF,读出来要么空、要么一串「ࠫڱࢺ」这种阿拉伯/叙利亚字母。
  152. * 真因是中文 PDF 几乎都用 Identity-H 编码:正文里存的是**字形编号**,
  153. * 不是 Unicode。想知道编号对应哪个字,必须查字体对象里的 /ToUnicode 映射表。
  154. * 老实现直接把编号当码位用,两种结局:编号落在私用区(被判成乱码),
  155. * 或者落在别的文字区(判成"可读"的错字)—— 后者更糟,模型会照着错字编内容。
  156. *
  157. * 做法(只覆盖中文 PDF 的主流写法,够用且不引第三方库):
  158. * 1. 顺序扫 `N 0 obj ... endobj` 建对象表,流按 stream/endstream 切;
  159. * 2. 找带 /ToUnicode 的字体对象,解析它的 CMap(beginbfchar / beginbfrange);
  160. * 3. 页面资源里 `/Font << /F1 5 0 R >>` 建「字体名 → 字体对象」;
  161. * 4. 内容流里跟 Tf 切字体,Tj/TJ 的字符串按该字体的表逐码翻译。
  162. * 没有 ToUnicode 的(扫描件、少数导出工具)保持原样,最后由可读性判据
  163. * 决定是"能用"还是"老实说读不了"——宁可报读不了,也不喂乱码。
  164. */
  165. function decodePdfString (raw) {
  166. // PDF 字符串里的转义:\n \r \t \( \) \\ 和三位八进制
  167. let out = ''
  168. for (let i = 0; i < raw.length; i++) {
  169. const ch = raw[i]
  170. if (ch !== '\\') { out += ch; continue }
  171. const next = raw[++i]
  172. if (next === 'n') out += '\n'
  173. else if (next === 'r') out += '\r'
  174. else if (next === 't') out += '\t'
  175. else if (next === 'b' || next === 'f') out += ' '
  176. else if (next >= '0' && next <= '7') {
  177. let oct = next
  178. for (let k = 0; k < 2 && raw[i + 1] >= '0' && raw[i + 1] <= '7'; k++) oct += raw[++i]
  179. out += String.fromCharCode(parseInt(oct, 8))
  180. } else if (next === '\n') { /* 行尾续行,忽略 */ } else out += next
  181. }
  182. return out
  183. }
  184. function hexToBytes (hex) {
  185. const clean = String(hex || '').replace(/\s+/g, '')
  186. let out = ''
  187. for (let i = 0; i + 2 <= clean.length; i += 2) {
  188. out += String.fromCharCode(parseInt(clean.slice(i, i + 2), 16))
  189. }
  190. return out
  191. }
  192. /** hex(UTF-16BE)→ 字符串,ToUnicode 的右值都是这个形状 */
  193. function hexToText (hex) {
  194. let out = ''
  195. for (let i = 0; i + 4 <= hex.length; i += 4) {
  196. const code = parseInt(hex.slice(i, i + 4), 16)
  197. if (Number.isFinite(code) && code) out += String.fromCharCode(code)
  198. }
  199. return out
  200. }
  201. /** `N 0 obj ... endobj` 的对象表。不做对象流(ObjStm),中文 PDF 极少见。 */
  202. function pdfObjects (buf) {
  203. const text = buf.toString('latin1')
  204. const objs = new Map()
  205. const re = /(\d+)\s+0\s+obj\b/g
  206. let m
  207. while ((m = re.exec(text))) {
  208. const num = Number(m[1])
  209. const bodyStart = m.index + m[0].length
  210. const end = text.indexOf('endobj', bodyStart)
  211. if (end < 0) break
  212. const body = text.slice(bodyStart, end)
  213. let stream = null
  214. const sm = /stream\r?\n/.exec(body)
  215. if (sm) {
  216. const dataStart = bodyStart + sm.index + sm[0].length
  217. const dataEnd = text.indexOf('endstream', dataStart)
  218. if (dataEnd >= 0) stream = buf.subarray(dataStart, dataEnd)
  219. }
  220. objs.set(num, { body, stream })
  221. re.lastIndex = end
  222. }
  223. return objs
  224. }
  225. function pdfStreamData (obj) {
  226. if (!obj || !obj.stream) return null
  227. if (!/\/FlateDecode/.test(obj.body)) {
  228. // 别的滤镜(DCT 图片之类)不是文本流,跳过
  229. return /\/Filter/.test(obj.body) ? null : obj.stream
  230. }
  231. try { return zlib.inflateSync(obj.stream) } catch { return null }
  232. }
  233. /** 解析一份 ToUnicode CMap */
  234. function parseToUnicode (data) {
  235. const map = new Map()
  236. const text = data.toString('latin1')
  237. for (const block of text.matchAll(/beginbfchar([\s\S]*?)endbfchar/g)) {
  238. for (const pair of block[1].matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g)) {
  239. map.set(parseInt(pair[1], 16), hexToText(pair[2]))
  240. }
  241. }
  242. for (const block of text.matchAll(/beginbfrange([\s\S]*?)endbfrange/g)) {
  243. const body = block[1]
  244. for (const r of body.matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g)) {
  245. const lo = parseInt(r[1], 16)
  246. const hi = parseInt(r[2], 16)
  247. const dst = parseInt(r[3], 16)
  248. if (!(hi >= lo) || hi - lo > 0xffff) continue
  249. for (let c = lo; c <= hi; c++) map.set(c, String.fromCharCode(dst + (c - lo)))
  250. }
  251. for (const r of body.matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*\[([\s\S]*?)\]/g)) {
  252. const lo = parseInt(r[1], 16)
  253. const items = [...r[3].matchAll(/<([0-9A-Fa-f]+)>/g)].map((x) => hexToText(x[1]))
  254. items.forEach((s, i) => map.set(lo + i, s))
  255. }
  256. }
  257. return map
  258. }
  259. /**
  260. * 字体上下文:字体对象 → {ToUnicode 表, 是否双字节},以及"某段资源里的
  261. * `/Font << /F1 5 0 R >>` → 名字到字体的映射"。
  262. *
  263. * 必须按页取映射,不能全局合并:子集字体(AAAAAA+MicrosoftYaHei)每页一套,
  264. * 编号空间各自从 1 开始,全局合并会让第 3 页的 /F1 覆盖第 1 页的 /F1,
  265. * 解出来就是"字都对、顺序全乱"的假中文 —— 比乱码更危险,因为看起来像能读。
  266. */
  267. function fontContext (objs) {
  268. const cache = new Map()
  269. const fontOf = (num) => {
  270. if (cache.has(num)) return cache.get(num)
  271. const obj = objs.get(num)
  272. let font = null
  273. if (obj) {
  274. const tu = /\/ToUnicode\s+(\d+)\s+0\s+R/.exec(obj.body)
  275. if (tu) {
  276. const data = pdfStreamData(objs.get(Number(tu[1])))
  277. if (data) {
  278. font = {
  279. map: parseToUnicode(data),
  280. twoByte: /\/Encoding\s*\/Identity-[HV]/.test(obj.body) || /\/Subtype\s*\/Type0/.test(obj.body)
  281. }
  282. }
  283. }
  284. }
  285. cache.set(num, font)
  286. return font
  287. }
  288. const fontsFrom = (text) => {
  289. const byName = new Map()
  290. for (const block of String(text || '').matchAll(/\/Font\s*<<([\s\S]{0,6000}?)>>/g)) {
  291. for (const f of block[1].matchAll(/\/([A-Za-z0-9#+._-]+)\s+(\d+)\s+0\s+R/g)) {
  292. const font = fontOf(Number(f[2]))
  293. if (font) byName.set(f[1], font)
  294. }
  295. }
  296. return byName
  297. }
  298. return { fontOf, fontsFrom }
  299. }
  300. /** 一段 PDF 字符串(latin1 视角的字节)按字体表翻译成文字 */
  301. function pdfBytesToText (raw, font) {
  302. const bytes = Buffer.from(String(raw || ''), 'latin1')
  303. if (!font || !font.map.size) return bytes.toString('latin1')
  304. const step = font.twoByte ? 2 : 1
  305. let out = ''
  306. for (let i = 0; i < bytes.length; i += step) {
  307. const code = step === 2 ? (bytes[i] << 8) | (bytes[i + 1] || 0) : bytes[i]
  308. const hit = font.map.get(code)
  309. if (hit !== undefined) out += hit
  310. }
  311. return out
  312. }
  313. /** 内容流 → 文字。ctx 为 null 时退化成"码位直读"(老行为)。 */
  314. function decodePdfContent (text, ctx) {
  315. let font = null
  316. let out = ''
  317. // 逐字定位的排版(每写一个字就 Td 一次)不能一律当换行,否则标题会被拆成
  318. // 一列单字("荔\n园\n教\n育…")。Td 的第二个参数是纵向位移,≈0 就是同一行。
  319. const re = /\/(?<tf>[A-Za-z0-9#+._-]+)\s+[-\d.]+\s+Tf|\((?<tjs>(?:\\.|[^\\()])*)\)\s*Tj|\[(?<tjarr>(?:[^\]\\]|\\.)*)\]\s*TJ|<(?<hex>[0-9A-Fa-f\s]+)>\s*Tj|(?<tx>-?[\d.]+)\s+(?<ty>-?[\d.]+)\s+(?:Td|TD)|(?<brk>T\*|ET)/g
  320. let m
  321. while ((m = re.exec(text))) {
  322. const g = m.groups
  323. if (g.tf !== undefined) {
  324. font = (ctx && ctx.byName.get(g.tf)) || null
  325. } else if (g.tjs !== undefined) {
  326. out += pdfBytesToText(decodePdfString(g.tjs), font)
  327. } else if (g.tjarr !== undefined) {
  328. for (const s of g.tjarr.matchAll(/\(((?:\\.|[^\\()])*)\)|<([0-9A-Fa-f\s]+)>/g)) {
  329. out += pdfBytesToText(s[1] !== undefined ? decodePdfString(s[1]) : hexToBytes(s[2]), font)
  330. }
  331. } else if (g.hex !== undefined) {
  332. out += pdfBytesToText(hexToBytes(g.hex), font)
  333. } else if (g.ty !== undefined) {
  334. if (Math.abs(Number(g.ty)) >= 1) out += '\n'
  335. } else {
  336. out += '\n'
  337. }
  338. }
  339. return out
  340. }
  341. /**
  342. * 可读性打分:ASCII / 汉字 / 中文标点 / 全角 / 拉丁扩展 之外的一律算"不像人话"。
  343. * 老实现只把控制字符和私用区算坏,于是「ࠫڱࢺ」这种别的文字区误判成可读。
  344. */
  345. function readableRatio (s) {
  346. if (!s) return 0
  347. let good = 0
  348. let total = 0
  349. for (const ch of s) {
  350. const c = ch.codePointAt(0)
  351. if (ch === '\n' || ch === '\t' || ch === ' ') { total++; good++; continue }
  352. total++
  353. if (c >= 0x20 && c < 0x7f) good++
  354. else if (c >= 0x4e00 && c <= 0x9fff) good++
  355. else if (c >= 0x3000 && c <= 0x303f) good++
  356. else if (c >= 0xff00 && c <= 0xffef) good++
  357. else if (c >= 0x00c0 && c <= 0x024f) good++
  358. else if (c === 0x2018 || c === 0x2019 || c === 0x201c || c === 0x201d) good++
  359. else if (c === 0x2013 || c === 0x2014 || c === 0x2026 || c === 0x00b7) good++
  360. }
  361. return total ? good / total : 0
  362. }
  363. /** 逐页取"内容流 + 该页自己的字体表";没有页对象时返回空,由调用方退回全流扫描 */
  364. function pdfPageJobs (objs, ctx) {
  365. const jobs = []
  366. for (const obj of objs.values()) {
  367. if (!/\/Type\s*\/Page\b(?!s)/.test(obj.body)) continue
  368. let resBody = obj.body
  369. const resRef = /\/Resources\s+(\d+)\s+0\s+R/.exec(obj.body)
  370. if (resRef) {
  371. const r = objs.get(Number(resRef[1]))
  372. if (r) resBody += `\n${r.body}`
  373. }
  374. const byName = ctx.fontsFrom(resBody)
  375. const refs = []
  376. const one = /\/Contents\s+(\d+)\s+0\s+R/.exec(obj.body)
  377. if (one) refs.push(Number(one[1]))
  378. const arr = /\/Contents\s*\[([^\]]*)\]/.exec(obj.body)
  379. if (arr) for (const r of arr[1].matchAll(/(\d+)\s+0\s+R/g)) refs.push(Number(r[1]))
  380. for (const num of refs) {
  381. const c = objs.get(num)
  382. const data = c ? pdfStreamData(c) : null
  383. if (data) jobs.push({ data, byName })
  384. }
  385. }
  386. return jobs
  387. }
  388. /** 没有页对象(少见)或页里没取到流:退回按对象顺序扫所有文本流 */
  389. function pdfStreamJobs (buf, byName) {
  390. const jobs = []
  391. let pos = 0
  392. while (true) {
  393. const s = buf.indexOf('stream', pos)
  394. if (s < 0) break
  395. const e = buf.indexOf('endstream', s)
  396. if (e < 0) break
  397. let dataStart = s + 6
  398. if (buf[dataStart] === 0x0d) dataStart++
  399. if (buf[dataStart] === 0x0a) dataStart++
  400. const dict = buf.toString('latin1', Math.max(0, s - 400), s)
  401. // 图片流不是文字:20MB 的扫描件里有几十条 JPEG,硬拿文本正则去扫会
  402. // 把 V8 的正则栈跑爆(Maximum call stack size exceeded)。
  403. if (/\/Subtype\s*\/Image/.test(dict)) { pos = e + 9; continue }
  404. let data = buf.subarray(dataStart, e)
  405. if (data.length <= 8 * 1024 * 1024) {
  406. if (/\/FlateDecode/.test(dict)) {
  407. try { data = zlib.inflateSync(data) } catch { pos = e + 9; continue }
  408. }
  409. jobs.push({ data, byName })
  410. }
  411. pos = e + 9
  412. }
  413. return jobs
  414. }
  415. function readPdf (file) {
  416. const buf = fs.readFileSync(file)
  417. if (buf.subarray(0, 5).toString() !== '%PDF-') throw new Error('不是有效 PDF')
  418. const latin = buf.toString('latin1')
  419. const pages = (latin.match(/\/Type\s*\/Page[^s]/g) || []).length
  420. const objs = pdfObjects(buf)
  421. const ctx = fontContext(objs)
  422. const globalByName = ctx.fontsFrom([...objs.values()].map((o) => o.body).join('\n'))
  423. let jobs = pdfPageJobs(objs, ctx)
  424. if (!jobs.length) jobs = pdfStreamJobs(buf, globalByName)
  425. const mapped = []
  426. const raw = []
  427. for (const job of jobs) {
  428. const text = job.data.toString('latin1')
  429. if (!/\bTj\b|\bTJ\b/.test(text)) continue
  430. try {
  431. const m1 = decodePdfContent(text, job.byName.size ? job : null)
  432. const m2 = decodePdfContent(text, null)
  433. if (m1.trim()) mapped.push(m1)
  434. if (m2.trim()) raw.push(m2)
  435. } catch {
  436. // 单条流解析失败不影响整份文档:跳过它,别的页面照样能读
  437. }
  438. }
  439. const norm = (arr) => arr.join('\n').replace(/\n{3,}/g, '\n\n').trim()
  440. const textMapped = norm(mapped)
  441. const textRaw = norm(raw)
  442. // 有 ToUnicode 就优先用映射结果;映射出来反而不如直读(少见:表是错的)就用直读
  443. const text = readableRatio(textMapped) >= readableRatio(textRaw) ? textMapped : textRaw
  444. const ratio = Math.max(readableRatio(textMapped), readableRatio(textRaw))
  445. const readable = text.length > 0 && ratio >= 0.85
  446. return {
  447. kind: 'pdf',
  448. pages,
  449. chars: text.length,
  450. text: readable ? text : '',
  451. readable,
  452. hint: readable
  453. ? ''
  454. : '这个 PDF 里没有可提取的文字层(扫描件,或字体没有内嵌 Unicode 映射)。不要猜测内容:请让老师把源文件(Word/PPT)发来,或说明只能看页数。'
  455. }
  456. }
  457. // ------------------------------------------------------------------ 写 docx
  458. const PARA = (text, style) => {
  459. const pPr = style ? `<w:pPr><w:pStyle w:val="${style}"/></w:pPr>` : ''
  460. const runs = String(text).split('\n').map((line) => `<w:r><w:t xml:space="preserve">${XESC(line)}</w:t></w:r>`).join('')
  461. return `<w:p>${pPr}${runs}</w:p>`
  462. }
  463. const TABLE = (rows) => {
  464. const border = 'w:val="single" w:sz="4" w:space="0" w:color="999999"'
  465. const borders = `<w:tblBorders><w:top ${border}/><w:left ${border}/><w:bottom ${border}/><w:right ${border}/><w:insideH ${border}/><w:insideV ${border}/></w:tblBorders>`
  466. const body = rows.map((cells, ri) => `<w:tr>${cells.map((c) => `<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${PARA(c, ri === 0 ? 'TableHead' : '')}</w:tc>`).join('')}</w:tr>`).join('')
  467. return `<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/>${borders}</w:tblPr>${body}</w:tbl><w:p/>`
  468. }
  469. function buildDocx ({ title = '', blocks = [] }) {
  470. const body = []
  471. if (title) body.push(PARA(title, 'Title'))
  472. for (const b of blocks) {
  473. if (typeof b === 'string') { body.push(PARA(b)); continue }
  474. if (!b) continue
  475. if (b.type === 'heading') body.push(PARA(b.text || '', `Heading${Math.min(3, Math.max(1, Number(b.level) || 1))}`))
  476. else if (b.type === 'bullet') body.push(PARA(b.text || '', 'ListParagraph'))
  477. else if (b.type === 'table') body.push(TABLE(b.rows || []))
  478. else if (b.type === 'pageBreak') body.push('<w:p><w:r><w:br w:type="page"/></w:r></w:p>')
  479. else body.push(PARA(b.text || ''))
  480. }
  481. if (!body.length) body.push(PARA(''))
  482. const documentXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  483. <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${body.join('')}<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1418" w:bottom="1440" w:left="1418"/></w:sectPr></w:body></w:document>`
  484. const stylesXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  485. <w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  486. <w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:eastAsia="微软雅黑" w:hAnsi="Calibri"/><w:sz w:val="22"/><w:szCs w:val="22"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="300" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>
  487. <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
  488. <w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:before="240" w:after="240"/><w:jc w:val="center"/></w:pPr><w:rPr><w:b/><w:sz w:val="40"/></w:rPr></w:style>
  489. <w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:pPr><w:outlineLvl w:val="0"/><w:spacing w:before="240" w:after="120"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/></w:rPr></w:style>
  490. <w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/><w:pPr><w:outlineLvl w:val="1"/><w:spacing w:before="200" w:after="100"/></w:pPr><w:rPr><w:b/><w:sz w:val="26"/></w:rPr></w:style>
  491. <w:style w:type="paragraph" w:styleId="Heading3"><w:name w:val="heading 3"/><w:basedOn w:val="Normal"/><w:pPr><w:outlineLvl w:val="2"/></w:pPr><w:rPr><w:b/><w:sz w:val="23"/></w:rPr></w:style>
  492. <w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="420"/><w:contextualSpacing/></w:pPr></w:style>
  493. <w:style w:type="paragraph" w:styleId="TableHead"><w:name w:val="Table Head"/><w:basedOn w:val="Normal"/><w:rPr><w:b/></w:rPr></w:style>
  494. </w:styles>`
  495. const types = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  496. <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/></Types>`
  497. const rels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  498. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>`
  499. const docRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  500. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>`
  501. return zip([
  502. ['[Content_Types].xml', types],
  503. ['_rels/.rels', rels],
  504. ['word/document.xml', documentXml],
  505. ['word/styles.xml', stylesXml],
  506. ['word/_rels/document.xml.rels', docRels]
  507. ])
  508. }
  509. // ------------------------------------------------------------------ 写 xlsx
  510. function buildXlsx ({ sheets = [] }) {
  511. const list = sheets.length ? sheets : [{ name: 'Sheet1', rows: [] }]
  512. const sheetXml = (rows) => {
  513. const body = rows.map((cells, ri) => {
  514. const tds = cells.map((v, ci) => {
  515. const ref = `${String.fromCharCode(65 + (ci % 26))}${ri + 1}`
  516. if (typeof v === 'number' && Number.isFinite(v)) return `<c r="${ref}"><v>${v}</v></c>`
  517. if (v === null || v === undefined || v === '') return ''
  518. return `<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${XESC(v)}</t></is></c>`
  519. }).join('')
  520. return `<row r="${ri + 1}">${tds}</row>`
  521. }).join('')
  522. return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  523. <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${body}</sheetData></worksheet>`
  524. }
  525. const workbook = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  526. <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>${list.map((s, i) => `<sheet name="${XESC(String(s.name || `Sheet${i + 1}`).slice(0, 31))}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`).join('')}</sheets></workbook>`
  527. const wbRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  528. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${list.map((_s, i) => `<Relationship Id="rId${i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`).join('')}</Relationships>`
  529. const types = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  530. <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>${list.map((_s, i) => `<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join('')}</Types>`
  531. const rels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  532. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`
  533. const entries = [
  534. ['[Content_Types].xml', types],
  535. ['_rels/.rels', rels],
  536. ['xl/workbook.xml', workbook],
  537. ['xl/_rels/workbook.xml.rels', wbRels]
  538. ]
  539. list.forEach((s, i) => entries.push([`xl/worksheets/sheet${i + 1}.xml`, sheetXml(s.rows || [])]))
  540. return zip(entries)
  541. }
  542. // ------------------------------------------------------------------ HTML → PDF
  543. /** 找一个能无头打印 PDF 的浏览器(Chrome 优先,其次 Edge)。 */
  544. export function findBrowserExe (explicit) {
  545. const candidates = [explicit, process.env.CHROME_PATH,
  546. 'C:/Program Files/Google/Chrome/Application/chrome.exe',
  547. 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
  548. 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
  549. 'C:/Program Files/Microsoft/Edge/Application/msedge.exe',
  550. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  551. '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser'
  552. ].filter(Boolean)
  553. for (const p of candidates) {
  554. try { if (fs.statSync(p).isFile()) return p } catch { /* 继续找 */ }
  555. }
  556. return ''
  557. }
  558. export function htmlToPdf ({ htmlPath, pdfPath, browserExe }) {
  559. const exe = findBrowserExe(browserExe)
  560. if (!exe) throw new Error('这台电脑上没有找到 Chrome/Edge,无法把 HTML 打印成 PDF')
  561. const out = path.resolve(pdfPath)
  562. fs.mkdirSync(path.dirname(out), { recursive: true })
  563. const url = /^[a-z]+:\/\//i.test(htmlPath) ? htmlPath : `file:///${path.resolve(htmlPath).replace(/\\/g, '/')}`
  564. return new Promise((resolve, reject) => {
  565. execFile(exe, [
  566. '--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
  567. '--disable-extensions', '--print-to-pdf-no-header',
  568. `--print-to-pdf=${out}`, url
  569. ], { timeout: 90_000, windowsHide: true }, (err, _stdout, stderr) => {
  570. if (err && !fs.existsSync(out)) return reject(new Error(`打印 PDF 失败:${String(stderr || err.message).slice(0, 200)}`))
  571. if (!fs.existsSync(out)) return reject(new Error('打印结束但没有生成 PDF'))
  572. resolve({ file: out, bytes: fs.statSync(out).size, browser: exe })
  573. })
  574. })
  575. }
  576. /** HTML 转 PNG:给思维导图、板书这类要贴进课件或发群的图。 */
  577. export function htmlToPng ({ htmlPath, pngPath, browserExe, width = 1400, height = 900 }) {
  578. const exe = findBrowserExe(browserExe)
  579. if (!exe) throw new Error('这台电脑上没有找到 Chrome/Edge,无法把 HTML 截成图片')
  580. const out = path.resolve(pngPath)
  581. fs.mkdirSync(path.dirname(out), { recursive: true })
  582. const url = /^[a-z]+:\/\//i.test(htmlPath) ? htmlPath : `file:///${path.resolve(htmlPath).replace(/\\/g, '/')}`
  583. const w = Math.min(4000, Math.max(400, Number(width) || 1400))
  584. const h = Math.min(4000, Math.max(300, Number(height) || 900))
  585. return new Promise((resolve, reject) => {
  586. execFile(exe, [
  587. '--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
  588. '--disable-extensions', '--hide-scrollbars', '--force-device-scale-factor=2',
  589. `--window-size=${w},${h}`, `--screenshot=${out}`, url
  590. ], { timeout: 90_000, windowsHide: true }, (err, _stdout, stderr) => {
  591. if (!fs.existsSync(out)) return reject(new Error(`截图失败:${String(stderr || err.message).slice(0, 200)}`))
  592. resolve({ file: out, bytes: fs.statSync(out).size, width: w, height: h, browser: exe })
  593. })
  594. })
  595. }
  596. // ------------------------------------------------------------------ 对外
  597. export function readOfficeFile (file) { const ext = path.extname(file).toLowerCase()
  598. if (ext === '.docx' || ext === '.docm') return readDocx(file)
  599. if (ext === '.xlsx' || ext === '.xlsm') return readXlsx(file)
  600. if (ext === '.pptx' || ext === '.pptm') return readPptx(file)
  601. if (ext === '.pdf') return readPdf(file)
  602. if (ext === '.doc' || ext === '.xls' || ext === '.ppt') {
  603. throw new Error('这是 2003 老格式(.doc/.xls/.ppt),请在 WPS 里另存为 .docx/.xlsx/.pptx 后再处理')
  604. }
  605. throw new Error(`不支持读取 ${ext || '未知类型'};支持 docx / xlsx / pptx / pdf`)
  606. }
  607. export function writeDocx (file, spec) {
  608. const buf = buildDocx(spec || {})
  609. fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true })
  610. fs.writeFileSync(file, buf)
  611. return { file: path.resolve(file), bytes: buf.length }
  612. }
  613. export function writeXlsx (file, spec) {
  614. const buf = buildXlsx(spec || {})
  615. fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true })
  616. fs.writeFileSync(file, buf)
  617. return { file: path.resolve(file), bytes: buf.length }
  618. }
  619. // ------------------------------------------------------------------ 写 pptx
  620. // 手写 OOXML:一张能直接交给 WPS/PowerPoint 打开的 16:9 课件。
  621. // 只做老师真的会用的版式(封面/章节/要点/图文/结语),不做动画和转换效果。
  622. const SLIDE_W = 12192000
  623. const SLIDE_H = 6858000
  624. const MARGIN = 838200
  625. const FONT = '微软雅黑'
  626. const PPT_NS = 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
  627. 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
  628. 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'
  629. const SPRITE_HEAD = '<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
  630. '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>'
  631. const normColor = (v) => (/^[0-9a-f]{6}$/i.test(String(v || '').replace('#', '')) ? String(v).replace('#', '').toUpperCase() : '')
  632. /** 读图片像素尺寸(png / jpeg / gif);认不出来返回 null,调用方按 16:9 兜底。 */
  633. function imageSize (buf) {
  634. if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) {
  635. return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) }
  636. }
  637. if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8) {
  638. let i = 2
  639. while (i < buf.length - 9) {
  640. if (buf[i] !== 0xff) { i++; continue }
  641. const marker = buf[i + 1]
  642. if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
  643. return { w: buf.readUInt16BE(i + 7), h: buf.readUInt16BE(i + 5) }
  644. }
  645. i += 2 + buf.readUInt16BE(i + 2)
  646. }
  647. }
  648. if (buf.length > 10 && buf.toString('ascii', 0, 3) === 'GIF') {
  649. return { w: buf.readUInt16LE(6), h: buf.readUInt16LE(8) }
  650. }
  651. return null
  652. }
  653. function pptTheme (accent) {
  654. return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  655. <a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="CocoBuddy">
  656. <a:themeElements>
  657. <a:clrScheme name="CocoBuddy">
  658. <a:dk1><a:srgbClr val="1F2937"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>
  659. <a:dk2><a:srgbClr val="334155"/></a:dk2><a:lt2><a:srgbClr val="F1F5F9"/></a:lt2>
  660. <a:accent1><a:srgbClr val="${accent}"/></a:accent1><a:accent2><a:srgbClr val="0F766E"/></a:accent2>
  661. <a:accent3><a:srgbClr val="D97706"/></a:accent3><a:accent4><a:srgbClr val="7C3AED"/></a:accent4>
  662. <a:accent5><a:srgbClr val="DC2626"/></a:accent5><a:accent6><a:srgbClr val="0891B2"/></a:accent6>
  663. <a:hlink><a:srgbClr val="${accent}"/></a:hlink><a:folHlink><a:srgbClr val="7C3AED"/></a:folHlink>
  664. </a:clrScheme>
  665. <a:fontScheme name="CocoBuddy">
  666. <a:majorFont><a:latin typeface="Microsoft YaHei"/><a:ea typeface="${FONT}"/><a:cs typeface=""/></a:majorFont>
  667. <a:minorFont><a:latin typeface="Microsoft YaHei"/><a:ea typeface="${FONT}"/><a:cs typeface=""/></a:minorFont>
  668. </a:fontScheme>
  669. <a:fmtScheme name="CocoBuddy">
  670. <a:fillStyleLst>
  671. <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
  672. <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
  673. <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
  674. </a:fillStyleLst>
  675. <a:lnStyleLst>
  676. <a:ln w="6350" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>
  677. <a:ln w="12700" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>
  678. <a:ln w="19050" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>
  679. </a:lnStyleLst>
  680. <a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>
  681. <a:bgFillStyleLst>
  682. <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
  683. <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
  684. <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
  685. </a:bgFillStyleLst>
  686. </a:fmtScheme>
  687. </a:themeElements>
  688. <a:objectDefaults/><a:extraClrSchemeLst/>
  689. </a:theme>`
  690. }
  691. function pptMaster () {
  692. return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  693. <p:sldMaster ${PPT_NS}><p:cSld>
  694. <p:bg><p:bgPr><a:solidFill><a:schemeClr val="lt1"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>
  695. <p:spTree>${SPRITE_HEAD}</p:spTree></p:cSld>
  696. <p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>
  697. <p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst>
  698. <p:txStyles>
  699. <p:titleStyle><a:lvl1pPr><a:defRPr sz="4000" b="1"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="Microsoft YaHei"/><a:ea typeface="${FONT}"/></a:defRPr></a:lvl1pPr></p:titleStyle>
  700. <p:bodyStyle><a:lvl1pPr><a:defRPr sz="2000"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="Microsoft YaHei"/><a:ea typeface="${FONT}"/></a:defRPr></a:lvl1pPr></p:bodyStyle>
  701. <p:otherStyle><a:defPPr><a:defRPr lang="zh-CN"/></a:defPPr><a:lvl1pPr marL="0" algn="l"><a:defRPr sz="1800"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="Microsoft YaHei"/><a:ea typeface="${FONT}"/></a:defRPr></a:lvl1pPr></p:otherStyle>
  702. </p:txStyles></p:sldMaster>`
  703. }
  704. function pptLayout () {
  705. return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  706. <p:sldLayout ${PPT_NS} type="blank" preserve="1">
  707. <p:cSld name="空白"><p:spTree>${SPRITE_HEAD}</p:spTree></p:cSld>
  708. <p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>`
  709. }
  710. function shapeRect (id, name, x, y, cx, cy, fill, { rounded = false } = {}) {
  711. return `<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${name}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>
  712. <p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>
  713. <a:prstGeom prst="${rounded ? 'roundRect' : 'rect'}"><a:avLst/></a:prstGeom>
  714. <a:solidFill><a:srgbClr val="${fill}"/></a:solidFill><a:ln><a:noFill/></a:ln></p:spPr></p:sp>`
  715. }
  716. function shapeText (id, name, x, y, cx, cy, paras, { anchor = 't' } = {}) {
  717. const body = paras.map((p) => {
  718. const align = p.align || 'l'
  719. const bullet = p.bullet
  720. ? '<a:buFont typeface="Arial"/><a:buChar char="•"/>'
  721. : '<a:buNone/>'
  722. const indent = p.bullet ? ' marL="352425" indent="-352425"' : ''
  723. const before = p.spaceBefore ? `<a:spcBef><a:spcPts val="${p.spaceBefore}"/></a:spcBef>` : ''
  724. const after = p.spaceAfter ? `<a:spcAft><a:spcPts val="${p.spaceAfter}"/></a:spcAft>` : ''
  725. const props = `<a:rPr lang="zh-CN" altLang="en-US" sz="${p.size || 1800}" b="${p.bold ? 1 : 0}" dirty="0">` +
  726. `<a:solidFill><a:srgbClr val="${p.color || '1F2937'}"/></a:solidFill>` +
  727. `<a:latin typeface="Microsoft YaHei"/><a:ea typeface="${FONT}"/></a:rPr>`
  728. const text = XESC(p.text == null ? '' : p.text)
  729. const run = p.text === '' ? '' : `<a:r>${props}<a:t>${text}</a:t></a:r>`
  730. const end = `<a:endParaRPr lang="zh-CN" sz="${p.size || 1800}"/>`
  731. return `<a:p><a:pPr algn="${align}"${indent}>${before}${after}${bullet}</a:pPr>${run || '<a:r><a:rPr lang="zh-CN" sz="1200" dirty="0"/><a:t> </a:t></a:r>'}${end}</a:p>`
  732. }).join('')
  733. return `<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${name}"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>
  734. <p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></p:spPr>
  735. <p:txBody><a:bodyPr wrap="square" lIns="0" tIns="0" rIns="0" bIns="0" anchor="${anchor}"><a:normAutofit/></a:bodyPr>
  736. <a:lstStyle/>${body}</p:txBody></p:sp>`
  737. }
  738. function shapePic (id, name, rid, x, y, cx, cy) {
  739. return `<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${name}"/><p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr>
  740. <p:blipFill><a:blip r:embed="${rid}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>
  741. <p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`
  742. }
  743. /** 图片在框内等比缩放并居中(EMU)。 */
  744. function fitBox (imgW, imgH, boxW, boxH) {
  745. const src = imgW > 0 && imgH > 0 ? { w: imgW, h: imgH } : { w: 16, h: 9 }
  746. const ratio = Math.min(boxW / src.w, boxH / src.h)
  747. const w = Math.round(src.w * ratio)
  748. const h = Math.round(src.h * ratio)
  749. return { w, h, x: Math.round((boxW - w) / 2), y: Math.round((boxH - h) / 2) }
  750. }
  751. const slideWrap = (shapes) => `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  752. <p:sld ${PPT_NS}><p:cSld><p:spTree>${SPRITE_HEAD}${shapes}</p:spTree></p:cSld>
  753. <p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>`
  754. function buildPptx (spec) {
  755. const s = spec || {}
  756. const accent = normColor(s.accent) || '2563EB'
  757. const footer = String(s.footer || '').trim()
  758. const slides = Array.isArray(s.slides) ? s.slides.slice(0, 80) : []
  759. const list = []
  760. if (s.cover !== false) {
  761. list.push({ layout: 'cover', title: s.title || '', subtitle: s.subtitle || '', meta: s.meta || '' })
  762. }
  763. list.push(...slides)
  764. if (s.closing) list.push({ layout: 'closing', title: String(s.closing) })
  765. if (!list.length) list.push({ layout: 'cover', title: s.title || '未命名课件' })
  766. const media = [] // { name, buf, ext }
  767. const slideParts = []
  768. list.forEach((slide, idx) => {
  769. const layout = String(slide.layout || (slide.image ? 'image' : 'bullets'))
  770. const shapes = []
  771. const rels = []
  772. let ridCursor = 2 // rId1 给 slideLayout
  773. let shapeId = 2
  774. const pageNo = (color) => {
  775. shapes.push(shapeText(shapeId++, '页码', SLIDE_W - MARGIN - 900000, SLIDE_H - 500000, 900000, 300000,
  776. [{ text: `${idx + 1} / ${list.length}`, size: 1000, color: color || '9CA3AF', align: 'r' }]))
  777. }
  778. if (layout === 'cover') {
  779. shapes.push(shapeRect(shapeId++, '顶部色带', 0, 0, SLIDE_W, 152400, accent))
  780. shapes.push(shapeText(shapeId++, '主标题', MARGIN, 2011680, SLIDE_W - MARGIN * 2, 1600000,
  781. [{ text: slide.title || '未命名课件', size: 4400, bold: true, color: '1F2937' }], { anchor: 'b' }))
  782. if (slide.subtitle) {
  783. shapes.push(shapeText(shapeId++, '副标题', MARGIN, 3760000, SLIDE_W - MARGIN * 2, 900000,
  784. [{ text: slide.subtitle, size: 2000, color: '475569' }]))
  785. }
  786. shapes.push(shapeRect(shapeId++, '强调线', MARGIN, 3620000, 640080, 45720, accent))
  787. if (slide.meta) {
  788. shapes.push(shapeText(shapeId++, '署名', MARGIN, SLIDE_H - 1100000, SLIDE_W - MARGIN * 2, 400000,
  789. [{ text: slide.meta, size: 1300, color: '94A3B8' }]))
  790. }
  791. } else if (layout === 'section') {
  792. shapes.push(shapeRect(shapeId++, '章节底色', 0, 0, SLIDE_W, SLIDE_H, accent))
  793. shapes.push(shapeText(shapeId++, '章节标题', MARGIN, 2400000, SLIDE_W - MARGIN * 2, 1400000,
  794. [{ text: slide.title || '', size: 4000, bold: true, color: 'FFFFFF' }], { anchor: 'b' }))
  795. if (slide.subtitle) {
  796. shapes.push(shapeText(shapeId++, '章节说明', MARGIN, 3960000, SLIDE_W - MARGIN * 2, 800000,
  797. [{ text: slide.subtitle, size: 1800, color: 'E2E8F0' }]))
  798. }
  799. } else if (layout === 'closing') {
  800. shapes.push(shapeRect(shapeId++, '底色', 0, 0, SLIDE_W, SLIDE_H, 'F8FAFC'))
  801. shapes.push(shapeText(shapeId++, '结语', MARGIN, 2560320, SLIDE_W - MARGIN * 2, 1400000,
  802. [{ text: slide.title || '谢谢', size: 4000, bold: true, color: accent, align: 'ctr' }], { anchor: 'b' }))
  803. } else {
  804. // 内容页(要点 / 图文):标题 + 色条 + 正文
  805. const hasImage = !!slide.image
  806. shapes.push(shapeRect(shapeId++, '标题色块', MARGIN, 660000, 68580, 609600, accent))
  807. shapes.push(shapeText(shapeId++, '标题', MARGIN + 228600, 610000, SLIDE_W - MARGIN * 2 - 228600, 700000,
  808. [{ text: slide.title || '', size: 2800, bold: true, color: '1F2937' }], { anchor: 'ctr' }))
  809. const bullets = Array.isArray(slide.bullets)
  810. ? slide.bullets.map((b) => (typeof b === 'string' ? { text: b } : { text: b.text, level: b.level || 0 }))
  811. : (slide.text ? String(slide.text).split('\n').filter(Boolean).map((t) => ({ text: t })) : [])
  812. const bodyW = hasImage ? 4937760 : SLIDE_W - MARGIN * 2
  813. const bodyH = SLIDE_H - 1900000 - 500000
  814. const count = bullets.length || 1
  815. const size = count <= 3 ? 2400 : count <= 5 ? 2000 : count <= 7 ? 1800 : 1600
  816. if (bullets.length) {
  817. shapes.push(shapeText(shapeId++, '正文', MARGIN, 1800000, bodyW, bodyH,
  818. bullets.map((b, i) => ({
  819. text: b.text,
  820. size: b.level ? Math.max(1400, size - 200) : size,
  821. bullet: !b.level,
  822. color: '334155',
  823. spaceBefore: i === 0 ? 0 : 1200
  824. }))))
  825. }
  826. if (hasImage) {
  827. const imgPath = path.resolve(String(slide.image))
  828. let buf = null
  829. try { buf = fs.readFileSync(imgPath) } catch { buf = null }
  830. if (buf && buf.length) {
  831. let ext = path.extname(imgPath).toLowerCase().replace('.', '')
  832. if (ext === 'jpeg') ext = 'jpg'
  833. if (!['png', 'jpg', 'gif'].includes(ext)) ext = 'png'
  834. const imgSize = imageSize(buf)
  835. const name = `image${media.length + 1}.${ext}`
  836. media.push({ name, buf, ext })
  837. const boxW = 4876800
  838. const boxH = 4114800
  839. const box = fitBox(imgSize ? imgSize.w : 16, imgSize ? imgSize.h : 9, boxW, boxH)
  840. const boxX = SLIDE_W - MARGIN - boxW
  841. const boxY = 1800000
  842. shapes.push(shapeRect(shapeId++, '图片底板', boxX, boxY, boxW, boxH, 'F1F5F9'))
  843. const rid = `rId${ridCursor++}`
  844. rels.push([rid, `../media/${name}`])
  845. shapes.push(shapePic(shapeId++, '配图', rid, boxX + box.x, boxY + box.y, box.w, box.h))
  846. }
  847. }
  848. if (slide.note) {
  849. shapes.push(shapeText(shapeId++, '备注行', MARGIN, SLIDE_H - 900000, SLIDE_W - MARGIN * 2, 340000,
  850. [{ text: slide.note, size: 1200, color: '64748B' }]))
  851. }
  852. if (footer) {
  853. shapes.push(shapeText(shapeId++, '页脚', MARGIN, SLIDE_H - 500000, SLIDE_W / 2, 280000,
  854. [{ text: footer, size: 1000, color: 'B0B7C3' }]))
  855. }
  856. pageNo()
  857. }
  858. slideParts.push({ xml: slideWrap(shapes.join('')), rels })
  859. })
  860. const slideOverrides = slideParts.map((_p, i) =>
  861. `<Override PartName="/ppt/slides/slide${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>`).join('')
  862. const mediaDefaults = []
  863. const seenExt = new Set()
  864. for (const m of media) {
  865. if (seenExt.has(m.ext)) continue
  866. seenExt.add(m.ext)
  867. const type = m.ext === 'png' ? 'image/png' : m.ext === 'jpg' ? 'image/jpeg' : 'image/gif'
  868. mediaDefaults.push(`<Default Extension="${m.ext}" ContentType="${type}"/>`)
  869. }
  870. const types = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  871. <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
  872. <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
  873. <Default Extension="xml" ContentType="application/xml"/>
  874. ${mediaDefaults.join('')}
  875. <Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/>
  876. <Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/>
  877. <Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/>
  878. <Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>
  879. ${slideOverrides}
  880. </Types>`
  881. const presentation = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  882. <p:presentation ${PPT_NS} saveSubsetFonts="1">
  883. <p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst>
  884. <p:sldIdLst>${slideParts.map((_p, i) => `<p:sldId id="${256 + i}" r:id="rId${i + 2}"/>`).join('')}</p:sldIdLst>
  885. <p:sldSz cx="${SLIDE_W}" cy="${SLIDE_H}"/><p:notesSz cx="6858000" cy="9144000"/>
  886. </p:presentation>`
  887. const presRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  888. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  889. <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/>
  890. ${slideParts.map((_p, i) => `<Relationship Id="rId${i + 2}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide${i + 1}.xml"/>`).join('')}
  891. </Relationships>`
  892. const rootRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  893. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  894. <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/>
  895. </Relationships>`
  896. const masterRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  897. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  898. <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>
  899. <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>
  900. </Relationships>`
  901. const layoutRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  902. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  903. <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="../slideMasters/slideMaster1.xml"/>
  904. </Relationships>`
  905. const entries = [
  906. ['[Content_Types].xml', types],
  907. ['_rels/.rels', rootRels],
  908. ['ppt/presentation.xml', presentation],
  909. ['ppt/_rels/presentation.xml.rels', presRels],
  910. ['ppt/slideMasters/slideMaster1.xml', pptMaster()],
  911. ['ppt/slideMasters/_rels/slideMaster1.xml.rels', masterRels],
  912. ['ppt/slideLayouts/slideLayout1.xml', pptLayout()],
  913. ['ppt/slideLayouts/_rels/slideLayout1.xml.rels', layoutRels],
  914. ['ppt/theme/theme1.xml', pptTheme(accent)]
  915. ]
  916. slideParts.forEach((p, i) => {
  917. entries.push([`ppt/slides/slide${i + 1}.xml`, p.xml])
  918. const rels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  919. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  920. <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>
  921. ${p.rels.map(([rid, target]) => `<Relationship Id="${rid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="${target}"/>`).join('')}
  922. </Relationships>`
  923. entries.push([`ppt/slides/_rels/slide${i + 1}.xml.rels`, rels])
  924. })
  925. for (const m of media) entries.push([`ppt/media/${m.name}`, m.buf])
  926. return { buf: zip(entries), slideCount: slideParts.length }
  927. }
  928. export function writePptx (file, spec) {
  929. const built = buildPptx(spec)
  930. const out = path.resolve(file)
  931. fs.mkdirSync(path.dirname(out), { recursive: true })
  932. fs.writeFileSync(out, built.buf)
  933. return { file: out, bytes: built.buf.length, slideCount: built.slideCount }
  934. }