| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004 |
- /**
- * 本地 Office / PDF 读写(零依赖)
- * ------------------------------------------------
- * 能力边界(都是实测过的,不要在这里写"看起来能"的功能):
- * - docx:读正文/表格文字;写标题、段落、项目符号、表格
- * - xlsx:读单元格值;写多表、纯文本+数字
- * - pptx:只读(按页提取文字);写 pptx 由 cococlass 平台负责
- * - pdf :提取文字(文字型 PDF);HTML → PDF 用本机 Chrome/Edge 打印
- *
- * 为什么不用 COM 驱动 WPS:COM 会执行任意本地代码,客户端安全策略默认拦截,
- * 与其写一段在多数机器上跑不通的脚本,不如直接改文件——老师要的是结果。
- */
- import fs from 'node:fs'
- import path from 'node:path'
- import zlib from 'node:zlib'
- import { execFile } from 'node:child_process'
- import { unzip, zip } from './zip.mjs'
- const XESC = (s) => String(s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- const XUNESC = (s) => String(s)
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, "'")
- .replace(/&#(\d+);/g, (_m, d) => String.fromCodePoint(Number(d)))
- .replace(/&/g, '&')
- /** 从 XML 里按标签取纯文字(保留段落换行)。 */
- function textFromXml (xml, { para = 'w:p', text = 'w:t', breakTag = 'w:br' } = {}) {
- const lines = []
- const paraRe = new RegExp(`<${para}[\\s>][\\s\\S]*?</${para}>|<${para}/>`, 'g')
- const blocks = xml.match(paraRe) || [xml]
- for (const block of blocks) {
- let line = ''
- const tokenRe = new RegExp(`<${text}(?:\\s[^>]*)?>([\\s\\S]*?)</${text}>|<${breakTag}\\s*/>|<w:tab\\s*/>`, 'g')
- let m
- while ((m = tokenRe.exec(block))) {
- if (m[1] !== undefined) line += XUNESC(m[1])
- else if (m[0].startsWith('<w:tab')) line += '\t'
- else line += '\n'
- }
- if (line.trim()) lines.push(line)
- }
- return lines.join('\n')
- }
- // ------------------------------------------------------------------ docx 读
- function readDocx (file) {
- const parts = unzip(fs.readFileSync(file))
- const doc = parts.get('word/document.xml')
- if (!doc) throw new Error('这个 .docx 里找不到正文(可能不是 Word 文件,或者是老式 .doc)')
- const xml = doc.toString('utf8')
- const body = textFromXml(xml)
- // 表格单独抽出来,老师最常问"这张表里第三列是什么"
- const tables = []
- const tblRe = /<w:tbl>[\s\S]*?<\/w:tbl>/g
- let t
- while ((t = tblRe.exec(xml))) {
- const rows = []
- const rowRe = /<w:tr[\s>][\s\S]*?<\/w:tr>/g
- let r
- while ((r = rowRe.exec(t[0]))) {
- const cells = []
- const cellRe = /<w:tc>[\s\S]*?<\/w:tc>/g
- let c
- while ((c = cellRe.exec(r[0]))) cells.push(textFromXml(c[0]).replace(/\n/g, ' ').trim())
- rows.push(cells)
- }
- tables.push(rows)
- }
- return { kind: 'docx', text: body, tables, chars: body.length }
- }
- // ------------------------------------------------------------------ xlsx 读
- function colIndex (ref) {
- const letters = (ref.match(/^[A-Z]+/) || ['A'])[0]
- let n = 0
- for (const ch of letters) n = n * 26 + (ch.charCodeAt(0) - 64)
- return n - 1
- }
- function readXlsx (file) {
- const parts = unzip(fs.readFileSync(file))
- const shared = []
- const sst = parts.get('xl/sharedStrings.xml')
- if (sst) {
- const re = /<si>([\s\S]*?)<\/si>/g
- let m
- while ((m = re.exec(sst.toString('utf8')))) {
- const texts = [...m[1].matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((x) => XUNESC(x[1]))
- shared.push(texts.join(''))
- }
- }
- // 表名 ↔ 文件:先读 workbook 的 sheet 顺序,找不到就按文件名排序
- const sheets = []
- const wb = parts.get('xl/workbook.xml')
- const names = wb ? [...wb.toString('utf8').matchAll(/<sheet[^>]*name="([^"]*)"/g)].map((m) => XUNESC(m[1])) : []
- const sheetFiles = [...parts.keys()].filter((k) => /^xl\/worksheets\/sheet\d+\.xml$/.test(k))
- .sort((a, b) => Number(a.match(/(\d+)\.xml$/)[1]) - Number(b.match(/(\d+)\.xml$/)[1]))
- for (let i = 0; i < sheetFiles.length; i++) {
- const xml = parts.get(sheetFiles[i]).toString('utf8')
- const rows = []
- const rowRe = /<row[^>]*>([\s\S]*?)<\/row>/g
- let rm
- while ((rm = rowRe.exec(xml))) {
- const cells = []
- const cellRe = /<c([^>]*)>([\s\S]*?)<\/c>|<c([^>]*)\/>/g
- let cm
- while ((cm = cellRe.exec(rm[1]))) {
- const attrs = cm[1] || cm[3] || ''
- const inner = cm[2] || ''
- const ref = (attrs.match(/r="([A-Z]+\d+)"/) || [])[1]
- const type = (attrs.match(/t="([^"]+)"/) || [])[1]
- let value = ''
- if (type === 'inlineStr') {
- value = [...inner.matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((x) => XUNESC(x[1])).join('')
- } else {
- const v = (inner.match(/<v>([\s\S]*?)<\/v>/) || [])[1]
- if (v !== undefined) value = type === 's' ? (shared[Number(v)] ?? '') : XUNESC(v)
- }
- const idx = ref ? colIndex(ref) : cells.length
- cells[idx] = value
- }
- for (let k = 0; k < cells.length; k++) if (cells[k] === undefined) cells[k] = ''
- if (cells.some((c) => c !== '')) rows.push(cells)
- }
- sheets.push({ name: names[i] || sheetFiles[i].replace(/^xl\/worksheets\//, ''), rows })
- }
- return { kind: 'xlsx', sheets, sheetCount: sheets.length }
- }
- // ------------------------------------------------------------------ pptx 读
- function readPptx (file) {
- const parts = unzip(fs.readFileSync(file))
- const files = [...parts.keys()]
- .filter((k) => /^ppt\/slides\/slide\d+\.xml$/.test(k))
- .sort((a, b) => Number(a.match(/(\d+)\.xml$/)[1]) - Number(b.match(/(\d+)\.xml$/)[1]))
- if (!files.length) throw new Error('这个 .pptx 里没有幻灯片(可能是 .ppt 老格式)')
- const slides = files.map((k, i) => {
- const xml = parts.get(k).toString('utf8')
- const paras = []
- for (const p of xml.match(/<a:p>[\s\S]*?<\/a:p>/g) || []) {
- const line = [...p.matchAll(/<a:t(?:\s[^>]*)?>([\s\S]*?)<\/a:t>/g)].map((m) => XUNESC(m[1])).join('')
- if (line.trim()) paras.push(line)
- }
- return { index: i + 1, texts: paras }
- })
- return { kind: 'pptx', slideCount: slides.length, slides }
- }
- // ------------------------------------------------------------------ pdf 读
- /*
- * 为什么要这么麻烦(2026-11-19 现场):
- * 老师从飞书下载的 PDF,读出来要么空、要么一串「ࠫڱࢺ」这种阿拉伯/叙利亚字母。
- * 真因是中文 PDF 几乎都用 Identity-H 编码:正文里存的是**字形编号**,
- * 不是 Unicode。想知道编号对应哪个字,必须查字体对象里的 /ToUnicode 映射表。
- * 老实现直接把编号当码位用,两种结局:编号落在私用区(被判成乱码),
- * 或者落在别的文字区(判成"可读"的错字)—— 后者更糟,模型会照着错字编内容。
- *
- * 做法(只覆盖中文 PDF 的主流写法,够用且不引第三方库):
- * 1. 顺序扫 `N 0 obj ... endobj` 建对象表,流按 stream/endstream 切;
- * 2. 找带 /ToUnicode 的字体对象,解析它的 CMap(beginbfchar / beginbfrange);
- * 3. 页面资源里 `/Font << /F1 5 0 R >>` 建「字体名 → 字体对象」;
- * 4. 内容流里跟 Tf 切字体,Tj/TJ 的字符串按该字体的表逐码翻译。
- * 没有 ToUnicode 的(扫描件、少数导出工具)保持原样,最后由可读性判据
- * 决定是"能用"还是"老实说读不了"——宁可报读不了,也不喂乱码。
- */
- function decodePdfString (raw) {
- // PDF 字符串里的转义:\n \r \t \( \) \\ 和三位八进制
- let out = ''
- for (let i = 0; i < raw.length; i++) {
- const ch = raw[i]
- if (ch !== '\\') { out += ch; continue }
- const next = raw[++i]
- if (next === 'n') out += '\n'
- else if (next === 'r') out += '\r'
- else if (next === 't') out += '\t'
- else if (next === 'b' || next === 'f') out += ' '
- else if (next >= '0' && next <= '7') {
- let oct = next
- for (let k = 0; k < 2 && raw[i + 1] >= '0' && raw[i + 1] <= '7'; k++) oct += raw[++i]
- out += String.fromCharCode(parseInt(oct, 8))
- } else if (next === '\n') { /* 行尾续行,忽略 */ } else out += next
- }
- return out
- }
- function hexToBytes (hex) {
- const clean = String(hex || '').replace(/\s+/g, '')
- let out = ''
- for (let i = 0; i + 2 <= clean.length; i += 2) {
- out += String.fromCharCode(parseInt(clean.slice(i, i + 2), 16))
- }
- return out
- }
- /** hex(UTF-16BE)→ 字符串,ToUnicode 的右值都是这个形状 */
- function hexToText (hex) {
- let out = ''
- for (let i = 0; i + 4 <= hex.length; i += 4) {
- const code = parseInt(hex.slice(i, i + 4), 16)
- if (Number.isFinite(code) && code) out += String.fromCharCode(code)
- }
- return out
- }
- /** `N 0 obj ... endobj` 的对象表。不做对象流(ObjStm),中文 PDF 极少见。 */
- function pdfObjects (buf) {
- const text = buf.toString('latin1')
- const objs = new Map()
- const re = /(\d+)\s+0\s+obj\b/g
- let m
- while ((m = re.exec(text))) {
- const num = Number(m[1])
- const bodyStart = m.index + m[0].length
- const end = text.indexOf('endobj', bodyStart)
- if (end < 0) break
- const body = text.slice(bodyStart, end)
- let stream = null
- const sm = /stream\r?\n/.exec(body)
- if (sm) {
- const dataStart = bodyStart + sm.index + sm[0].length
- const dataEnd = text.indexOf('endstream', dataStart)
- if (dataEnd >= 0) stream = buf.subarray(dataStart, dataEnd)
- }
- objs.set(num, { body, stream })
- re.lastIndex = end
- }
- return objs
- }
- function pdfStreamData (obj) {
- if (!obj || !obj.stream) return null
- if (!/\/FlateDecode/.test(obj.body)) {
- // 别的滤镜(DCT 图片之类)不是文本流,跳过
- return /\/Filter/.test(obj.body) ? null : obj.stream
- }
- try { return zlib.inflateSync(obj.stream) } catch { return null }
- }
- /** 解析一份 ToUnicode CMap */
- function parseToUnicode (data) {
- const map = new Map()
- const text = data.toString('latin1')
- for (const block of text.matchAll(/beginbfchar([\s\S]*?)endbfchar/g)) {
- for (const pair of block[1].matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g)) {
- map.set(parseInt(pair[1], 16), hexToText(pair[2]))
- }
- }
- for (const block of text.matchAll(/beginbfrange([\s\S]*?)endbfrange/g)) {
- const body = block[1]
- for (const r of body.matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g)) {
- const lo = parseInt(r[1], 16)
- const hi = parseInt(r[2], 16)
- const dst = parseInt(r[3], 16)
- if (!(hi >= lo) || hi - lo > 0xffff) continue
- for (let c = lo; c <= hi; c++) map.set(c, String.fromCharCode(dst + (c - lo)))
- }
- for (const r of body.matchAll(/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*\[([\s\S]*?)\]/g)) {
- const lo = parseInt(r[1], 16)
- const items = [...r[3].matchAll(/<([0-9A-Fa-f]+)>/g)].map((x) => hexToText(x[1]))
- items.forEach((s, i) => map.set(lo + i, s))
- }
- }
- return map
- }
- /**
- * 字体上下文:字体对象 → {ToUnicode 表, 是否双字节},以及"某段资源里的
- * `/Font << /F1 5 0 R >>` → 名字到字体的映射"。
- *
- * 必须按页取映射,不能全局合并:子集字体(AAAAAA+MicrosoftYaHei)每页一套,
- * 编号空间各自从 1 开始,全局合并会让第 3 页的 /F1 覆盖第 1 页的 /F1,
- * 解出来就是"字都对、顺序全乱"的假中文 —— 比乱码更危险,因为看起来像能读。
- */
- function fontContext (objs) {
- const cache = new Map()
- const fontOf = (num) => {
- if (cache.has(num)) return cache.get(num)
- const obj = objs.get(num)
- let font = null
- if (obj) {
- const tu = /\/ToUnicode\s+(\d+)\s+0\s+R/.exec(obj.body)
- if (tu) {
- const data = pdfStreamData(objs.get(Number(tu[1])))
- if (data) {
- font = {
- map: parseToUnicode(data),
- twoByte: /\/Encoding\s*\/Identity-[HV]/.test(obj.body) || /\/Subtype\s*\/Type0/.test(obj.body)
- }
- }
- }
- }
- cache.set(num, font)
- return font
- }
- const fontsFrom = (text) => {
- const byName = new Map()
- for (const block of String(text || '').matchAll(/\/Font\s*<<([\s\S]{0,6000}?)>>/g)) {
- for (const f of block[1].matchAll(/\/([A-Za-z0-9#+._-]+)\s+(\d+)\s+0\s+R/g)) {
- const font = fontOf(Number(f[2]))
- if (font) byName.set(f[1], font)
- }
- }
- return byName
- }
- return { fontOf, fontsFrom }
- }
- /** 一段 PDF 字符串(latin1 视角的字节)按字体表翻译成文字 */
- function pdfBytesToText (raw, font) {
- const bytes = Buffer.from(String(raw || ''), 'latin1')
- if (!font || !font.map.size) return bytes.toString('latin1')
- const step = font.twoByte ? 2 : 1
- let out = ''
- for (let i = 0; i < bytes.length; i += step) {
- const code = step === 2 ? (bytes[i] << 8) | (bytes[i + 1] || 0) : bytes[i]
- const hit = font.map.get(code)
- if (hit !== undefined) out += hit
- }
- return out
- }
- /** 内容流 → 文字。ctx 为 null 时退化成"码位直读"(老行为)。 */
- function decodePdfContent (text, ctx) {
- let font = null
- let out = ''
- // 逐字定位的排版(每写一个字就 Td 一次)不能一律当换行,否则标题会被拆成
- // 一列单字("荔\n园\n教\n育…")。Td 的第二个参数是纵向位移,≈0 就是同一行。
- 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
- let m
- while ((m = re.exec(text))) {
- const g = m.groups
- if (g.tf !== undefined) {
- font = (ctx && ctx.byName.get(g.tf)) || null
- } else if (g.tjs !== undefined) {
- out += pdfBytesToText(decodePdfString(g.tjs), font)
- } else if (g.tjarr !== undefined) {
- for (const s of g.tjarr.matchAll(/\(((?:\\.|[^\\()])*)\)|<([0-9A-Fa-f\s]+)>/g)) {
- out += pdfBytesToText(s[1] !== undefined ? decodePdfString(s[1]) : hexToBytes(s[2]), font)
- }
- } else if (g.hex !== undefined) {
- out += pdfBytesToText(hexToBytes(g.hex), font)
- } else if (g.ty !== undefined) {
- if (Math.abs(Number(g.ty)) >= 1) out += '\n'
- } else {
- out += '\n'
- }
- }
- return out
- }
- /**
- * 可读性打分:ASCII / 汉字 / 中文标点 / 全角 / 拉丁扩展 之外的一律算"不像人话"。
- * 老实现只把控制字符和私用区算坏,于是「ࠫڱࢺ」这种别的文字区误判成可读。
- */
- function readableRatio (s) {
- if (!s) return 0
- let good = 0
- let total = 0
- for (const ch of s) {
- const c = ch.codePointAt(0)
- if (ch === '\n' || ch === '\t' || ch === ' ') { total++; good++; continue }
- total++
- if (c >= 0x20 && c < 0x7f) good++
- else if (c >= 0x4e00 && c <= 0x9fff) good++
- else if (c >= 0x3000 && c <= 0x303f) good++
- else if (c >= 0xff00 && c <= 0xffef) good++
- else if (c >= 0x00c0 && c <= 0x024f) good++
- else if (c === 0x2018 || c === 0x2019 || c === 0x201c || c === 0x201d) good++
- else if (c === 0x2013 || c === 0x2014 || c === 0x2026 || c === 0x00b7) good++
- }
- return total ? good / total : 0
- }
- /** 逐页取"内容流 + 该页自己的字体表";没有页对象时返回空,由调用方退回全流扫描 */
- function pdfPageJobs (objs, ctx) {
- const jobs = []
- for (const obj of objs.values()) {
- if (!/\/Type\s*\/Page\b(?!s)/.test(obj.body)) continue
- let resBody = obj.body
- const resRef = /\/Resources\s+(\d+)\s+0\s+R/.exec(obj.body)
- if (resRef) {
- const r = objs.get(Number(resRef[1]))
- if (r) resBody += `\n${r.body}`
- }
- const byName = ctx.fontsFrom(resBody)
- const refs = []
- const one = /\/Contents\s+(\d+)\s+0\s+R/.exec(obj.body)
- if (one) refs.push(Number(one[1]))
- const arr = /\/Contents\s*\[([^\]]*)\]/.exec(obj.body)
- if (arr) for (const r of arr[1].matchAll(/(\d+)\s+0\s+R/g)) refs.push(Number(r[1]))
- for (const num of refs) {
- const c = objs.get(num)
- const data = c ? pdfStreamData(c) : null
- if (data) jobs.push({ data, byName })
- }
- }
- return jobs
- }
- /** 没有页对象(少见)或页里没取到流:退回按对象顺序扫所有文本流 */
- function pdfStreamJobs (buf, byName) {
- const jobs = []
- let pos = 0
- while (true) {
- const s = buf.indexOf('stream', pos)
- if (s < 0) break
- const e = buf.indexOf('endstream', s)
- if (e < 0) break
- let dataStart = s + 6
- if (buf[dataStart] === 0x0d) dataStart++
- if (buf[dataStart] === 0x0a) dataStart++
- const dict = buf.toString('latin1', Math.max(0, s - 400), s)
- // 图片流不是文字:20MB 的扫描件里有几十条 JPEG,硬拿文本正则去扫会
- // 把 V8 的正则栈跑爆(Maximum call stack size exceeded)。
- if (/\/Subtype\s*\/Image/.test(dict)) { pos = e + 9; continue }
- let data = buf.subarray(dataStart, e)
- if (data.length <= 8 * 1024 * 1024) {
- if (/\/FlateDecode/.test(dict)) {
- try { data = zlib.inflateSync(data) } catch { pos = e + 9; continue }
- }
- jobs.push({ data, byName })
- }
- pos = e + 9
- }
- return jobs
- }
- function readPdf (file) {
- const buf = fs.readFileSync(file)
- if (buf.subarray(0, 5).toString() !== '%PDF-') throw new Error('不是有效 PDF')
- const latin = buf.toString('latin1')
- const pages = (latin.match(/\/Type\s*\/Page[^s]/g) || []).length
- const objs = pdfObjects(buf)
- const ctx = fontContext(objs)
- const globalByName = ctx.fontsFrom([...objs.values()].map((o) => o.body).join('\n'))
- let jobs = pdfPageJobs(objs, ctx)
- if (!jobs.length) jobs = pdfStreamJobs(buf, globalByName)
- const mapped = []
- const raw = []
- for (const job of jobs) {
- const text = job.data.toString('latin1')
- if (!/\bTj\b|\bTJ\b/.test(text)) continue
- try {
- const m1 = decodePdfContent(text, job.byName.size ? job : null)
- const m2 = decodePdfContent(text, null)
- if (m1.trim()) mapped.push(m1)
- if (m2.trim()) raw.push(m2)
- } catch {
- // 单条流解析失败不影响整份文档:跳过它,别的页面照样能读
- }
- }
- const norm = (arr) => arr.join('\n').replace(/\n{3,}/g, '\n\n').trim()
- const textMapped = norm(mapped)
- const textRaw = norm(raw)
- // 有 ToUnicode 就优先用映射结果;映射出来反而不如直读(少见:表是错的)就用直读
- const text = readableRatio(textMapped) >= readableRatio(textRaw) ? textMapped : textRaw
- const ratio = Math.max(readableRatio(textMapped), readableRatio(textRaw))
- const readable = text.length > 0 && ratio >= 0.85
- return {
- kind: 'pdf',
- pages,
- chars: text.length,
- text: readable ? text : '',
- readable,
- hint: readable
- ? ''
- : '这个 PDF 里没有可提取的文字层(扫描件,或字体没有内嵌 Unicode 映射)。不要猜测内容:请让老师把源文件(Word/PPT)发来,或说明只能看页数。'
- }
- }
- // ------------------------------------------------------------------ 写 docx
- const PARA = (text, style) => {
- const pPr = style ? `<w:pPr><w:pStyle w:val="${style}"/></w:pPr>` : ''
- const runs = String(text).split('\n').map((line) => `<w:r><w:t xml:space="preserve">${XESC(line)}</w:t></w:r>`).join('')
- return `<w:p>${pPr}${runs}</w:p>`
- }
- const TABLE = (rows) => {
- const border = 'w:val="single" w:sz="4" w:space="0" w:color="999999"'
- const borders = `<w:tblBorders><w:top ${border}/><w:left ${border}/><w:bottom ${border}/><w:right ${border}/><w:insideH ${border}/><w:insideV ${border}/></w:tblBorders>`
- 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('')
- return `<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/>${borders}</w:tblPr>${body}</w:tbl><w:p/>`
- }
- function buildDocx ({ title = '', blocks = [] }) {
- const body = []
- if (title) body.push(PARA(title, 'Title'))
- for (const b of blocks) {
- if (typeof b === 'string') { body.push(PARA(b)); continue }
- if (!b) continue
- if (b.type === 'heading') body.push(PARA(b.text || '', `Heading${Math.min(3, Math.max(1, Number(b.level) || 1))}`))
- else if (b.type === 'bullet') body.push(PARA(b.text || '', 'ListParagraph'))
- else if (b.type === 'table') body.push(TABLE(b.rows || []))
- else if (b.type === 'pageBreak') body.push('<w:p><w:r><w:br w:type="page"/></w:r></w:p>')
- else body.push(PARA(b.text || ''))
- }
- if (!body.length) body.push(PARA(''))
- const documentXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`
- const stylesXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
- <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>
- <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
- <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>
- <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>
- <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>
- <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>
- <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>
- <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>
- </w:styles>`
- const types = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`
- const rels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`
- const docRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`
- return zip([
- ['[Content_Types].xml', types],
- ['_rels/.rels', rels],
- ['word/document.xml', documentXml],
- ['word/styles.xml', stylesXml],
- ['word/_rels/document.xml.rels', docRels]
- ])
- }
- // ------------------------------------------------------------------ 写 xlsx
- function buildXlsx ({ sheets = [] }) {
- const list = sheets.length ? sheets : [{ name: 'Sheet1', rows: [] }]
- const sheetXml = (rows) => {
- const body = rows.map((cells, ri) => {
- const tds = cells.map((v, ci) => {
- const ref = `${String.fromCharCode(65 + (ci % 26))}${ri + 1}`
- if (typeof v === 'number' && Number.isFinite(v)) return `<c r="${ref}"><v>${v}</v></c>`
- if (v === null || v === undefined || v === '') return ''
- return `<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${XESC(v)}</t></is></c>`
- }).join('')
- return `<row r="${ri + 1}">${tds}</row>`
- }).join('')
- return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${body}</sheetData></worksheet>`
- }
- const workbook = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`
- const wbRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`
- const types = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`
- const rels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`
- const entries = [
- ['[Content_Types].xml', types],
- ['_rels/.rels', rels],
- ['xl/workbook.xml', workbook],
- ['xl/_rels/workbook.xml.rels', wbRels]
- ]
- list.forEach((s, i) => entries.push([`xl/worksheets/sheet${i + 1}.xml`, sheetXml(s.rows || [])]))
- return zip(entries)
- }
- // ------------------------------------------------------------------ HTML → PDF
- /** 找一个能无头打印 PDF 的浏览器(Chrome 优先,其次 Edge)。 */
- export function findBrowserExe (explicit) {
- const candidates = [explicit, process.env.CHROME_PATH,
- 'C:/Program Files/Google/Chrome/Application/chrome.exe',
- 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
- 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
- 'C:/Program Files/Microsoft/Edge/Application/msedge.exe',
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
- '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser'
- ].filter(Boolean)
- for (const p of candidates) {
- try { if (fs.statSync(p).isFile()) return p } catch { /* 继续找 */ }
- }
- return ''
- }
- export function htmlToPdf ({ htmlPath, pdfPath, browserExe }) {
- const exe = findBrowserExe(browserExe)
- if (!exe) throw new Error('这台电脑上没有找到 Chrome/Edge,无法把 HTML 打印成 PDF')
- const out = path.resolve(pdfPath)
- fs.mkdirSync(path.dirname(out), { recursive: true })
- const url = /^[a-z]+:\/\//i.test(htmlPath) ? htmlPath : `file:///${path.resolve(htmlPath).replace(/\\/g, '/')}`
- return new Promise((resolve, reject) => {
- execFile(exe, [
- '--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
- '--disable-extensions', '--print-to-pdf-no-header',
- `--print-to-pdf=${out}`, url
- ], { timeout: 90_000, windowsHide: true }, (err, _stdout, stderr) => {
- if (err && !fs.existsSync(out)) return reject(new Error(`打印 PDF 失败:${String(stderr || err.message).slice(0, 200)}`))
- if (!fs.existsSync(out)) return reject(new Error('打印结束但没有生成 PDF'))
- resolve({ file: out, bytes: fs.statSync(out).size, browser: exe })
- })
- })
- }
- /** HTML 转 PNG:给思维导图、板书这类要贴进课件或发群的图。 */
- export function htmlToPng ({ htmlPath, pngPath, browserExe, width = 1400, height = 900 }) {
- const exe = findBrowserExe(browserExe)
- if (!exe) throw new Error('这台电脑上没有找到 Chrome/Edge,无法把 HTML 截成图片')
- const out = path.resolve(pngPath)
- fs.mkdirSync(path.dirname(out), { recursive: true })
- const url = /^[a-z]+:\/\//i.test(htmlPath) ? htmlPath : `file:///${path.resolve(htmlPath).replace(/\\/g, '/')}`
- const w = Math.min(4000, Math.max(400, Number(width) || 1400))
- const h = Math.min(4000, Math.max(300, Number(height) || 900))
- return new Promise((resolve, reject) => {
- execFile(exe, [
- '--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
- '--disable-extensions', '--hide-scrollbars', '--force-device-scale-factor=2',
- `--window-size=${w},${h}`, `--screenshot=${out}`, url
- ], { timeout: 90_000, windowsHide: true }, (err, _stdout, stderr) => {
- if (!fs.existsSync(out)) return reject(new Error(`截图失败:${String(stderr || err.message).slice(0, 200)}`))
- resolve({ file: out, bytes: fs.statSync(out).size, width: w, height: h, browser: exe })
- })
- })
- }
- // ------------------------------------------------------------------ 对外
- export function readOfficeFile (file) { const ext = path.extname(file).toLowerCase()
- if (ext === '.docx' || ext === '.docm') return readDocx(file)
- if (ext === '.xlsx' || ext === '.xlsm') return readXlsx(file)
- if (ext === '.pptx' || ext === '.pptm') return readPptx(file)
- if (ext === '.pdf') return readPdf(file)
- if (ext === '.doc' || ext === '.xls' || ext === '.ppt') {
- throw new Error('这是 2003 老格式(.doc/.xls/.ppt),请在 WPS 里另存为 .docx/.xlsx/.pptx 后再处理')
- }
- throw new Error(`不支持读取 ${ext || '未知类型'};支持 docx / xlsx / pptx / pdf`)
- }
- export function writeDocx (file, spec) {
- const buf = buildDocx(spec || {})
- fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true })
- fs.writeFileSync(file, buf)
- return { file: path.resolve(file), bytes: buf.length }
- }
- export function writeXlsx (file, spec) {
- const buf = buildXlsx(spec || {})
- fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true })
- fs.writeFileSync(file, buf)
- return { file: path.resolve(file), bytes: buf.length }
- }
- // ------------------------------------------------------------------ 写 pptx
- // 手写 OOXML:一张能直接交给 WPS/PowerPoint 打开的 16:9 课件。
- // 只做老师真的会用的版式(封面/章节/要点/图文/结语),不做动画和转换效果。
- const SLIDE_W = 12192000
- const SLIDE_H = 6858000
- const MARGIN = 838200
- const FONT = '微软雅黑'
- const PPT_NS = 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
- 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
- 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'
- const SPRITE_HEAD = '<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>' +
- '<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>'
- const normColor = (v) => (/^[0-9a-f]{6}$/i.test(String(v || '').replace('#', '')) ? String(v).replace('#', '').toUpperCase() : '')
- /** 读图片像素尺寸(png / jpeg / gif);认不出来返回 null,调用方按 16:9 兜底。 */
- function imageSize (buf) {
- if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) {
- return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) }
- }
- if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8) {
- let i = 2
- while (i < buf.length - 9) {
- if (buf[i] !== 0xff) { i++; continue }
- const marker = buf[i + 1]
- if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
- return { w: buf.readUInt16BE(i + 7), h: buf.readUInt16BE(i + 5) }
- }
- i += 2 + buf.readUInt16BE(i + 2)
- }
- }
- if (buf.length > 10 && buf.toString('ascii', 0, 3) === 'GIF') {
- return { w: buf.readUInt16LE(6), h: buf.readUInt16LE(8) }
- }
- return null
- }
- function pptTheme (accent) {
- return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="CocoBuddy">
- <a:themeElements>
- <a:clrScheme name="CocoBuddy">
- <a:dk1><a:srgbClr val="1F2937"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>
- <a:dk2><a:srgbClr val="334155"/></a:dk2><a:lt2><a:srgbClr val="F1F5F9"/></a:lt2>
- <a:accent1><a:srgbClr val="${accent}"/></a:accent1><a:accent2><a:srgbClr val="0F766E"/></a:accent2>
- <a:accent3><a:srgbClr val="D97706"/></a:accent3><a:accent4><a:srgbClr val="7C3AED"/></a:accent4>
- <a:accent5><a:srgbClr val="DC2626"/></a:accent5><a:accent6><a:srgbClr val="0891B2"/></a:accent6>
- <a:hlink><a:srgbClr val="${accent}"/></a:hlink><a:folHlink><a:srgbClr val="7C3AED"/></a:folHlink>
- </a:clrScheme>
- <a:fontScheme name="CocoBuddy">
- <a:majorFont><a:latin typeface="Microsoft YaHei"/><a:ea typeface="${FONT}"/><a:cs typeface=""/></a:majorFont>
- <a:minorFont><a:latin typeface="Microsoft YaHei"/><a:ea typeface="${FONT}"/><a:cs typeface=""/></a:minorFont>
- </a:fontScheme>
- <a:fmtScheme name="CocoBuddy">
- <a:fillStyleLst>
- <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
- <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
- <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
- </a:fillStyleLst>
- <a:lnStyleLst>
- <a:ln w="6350" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>
- <a:ln w="12700" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>
- <a:ln w="19050" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>
- </a:lnStyleLst>
- <a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>
- <a:bgFillStyleLst>
- <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
- <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
- <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
- </a:bgFillStyleLst>
- </a:fmtScheme>
- </a:themeElements>
- <a:objectDefaults/><a:extraClrSchemeLst/>
- </a:theme>`
- }
- function pptMaster () {
- return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <p:sldMaster ${PPT_NS}><p:cSld>
- <p:bg><p:bgPr><a:solidFill><a:schemeClr val="lt1"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>
- <p:spTree>${SPRITE_HEAD}</p:spTree></p:cSld>
- <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"/>
- <p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst>
- <p:txStyles>
- <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>
- <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>
- <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>
- </p:txStyles></p:sldMaster>`
- }
- function pptLayout () {
- return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <p:sldLayout ${PPT_NS} type="blank" preserve="1">
- <p:cSld name="空白"><p:spTree>${SPRITE_HEAD}</p:spTree></p:cSld>
- <p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>`
- }
- function shapeRect (id, name, x, y, cx, cy, fill, { rounded = false } = {}) {
- return `<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${name}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>
- <p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>
- <a:prstGeom prst="${rounded ? 'roundRect' : 'rect'}"><a:avLst/></a:prstGeom>
- <a:solidFill><a:srgbClr val="${fill}"/></a:solidFill><a:ln><a:noFill/></a:ln></p:spPr></p:sp>`
- }
- function shapeText (id, name, x, y, cx, cy, paras, { anchor = 't' } = {}) {
- const body = paras.map((p) => {
- const align = p.align || 'l'
- const bullet = p.bullet
- ? '<a:buFont typeface="Arial"/><a:buChar char="•"/>'
- : '<a:buNone/>'
- const indent = p.bullet ? ' marL="352425" indent="-352425"' : ''
- const before = p.spaceBefore ? `<a:spcBef><a:spcPts val="${p.spaceBefore}"/></a:spcBef>` : ''
- const after = p.spaceAfter ? `<a:spcAft><a:spcPts val="${p.spaceAfter}"/></a:spcAft>` : ''
- const props = `<a:rPr lang="zh-CN" altLang="en-US" sz="${p.size || 1800}" b="${p.bold ? 1 : 0}" dirty="0">` +
- `<a:solidFill><a:srgbClr val="${p.color || '1F2937'}"/></a:solidFill>` +
- `<a:latin typeface="Microsoft YaHei"/><a:ea typeface="${FONT}"/></a:rPr>`
- const text = XESC(p.text == null ? '' : p.text)
- const run = p.text === '' ? '' : `<a:r>${props}<a:t>${text}</a:t></a:r>`
- const end = `<a:endParaRPr lang="zh-CN" sz="${p.size || 1800}"/>`
- 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>`
- }).join('')
- return `<p:sp><p:nvSpPr><p:cNvPr id="${id}" name="${name}"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>
- <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>
- <p:txBody><a:bodyPr wrap="square" lIns="0" tIns="0" rIns="0" bIns="0" anchor="${anchor}"><a:normAutofit/></a:bodyPr>
- <a:lstStyle/>${body}</p:txBody></p:sp>`
- }
- function shapePic (id, name, rid, x, y, cx, cy) {
- return `<p:pic><p:nvPicPr><p:cNvPr id="${id}" name="${name}"/><p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr>
- <p:blipFill><a:blip r:embed="${rid}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>
- <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>`
- }
- /** 图片在框内等比缩放并居中(EMU)。 */
- function fitBox (imgW, imgH, boxW, boxH) {
- const src = imgW > 0 && imgH > 0 ? { w: imgW, h: imgH } : { w: 16, h: 9 }
- const ratio = Math.min(boxW / src.w, boxH / src.h)
- const w = Math.round(src.w * ratio)
- const h = Math.round(src.h * ratio)
- return { w, h, x: Math.round((boxW - w) / 2), y: Math.round((boxH - h) / 2) }
- }
- const slideWrap = (shapes) => `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <p:sld ${PPT_NS}><p:cSld><p:spTree>${SPRITE_HEAD}${shapes}</p:spTree></p:cSld>
- <p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>`
- function buildPptx (spec) {
- const s = spec || {}
- const accent = normColor(s.accent) || '2563EB'
- const footer = String(s.footer || '').trim()
- const slides = Array.isArray(s.slides) ? s.slides.slice(0, 80) : []
- const list = []
- if (s.cover !== false) {
- list.push({ layout: 'cover', title: s.title || '', subtitle: s.subtitle || '', meta: s.meta || '' })
- }
- list.push(...slides)
- if (s.closing) list.push({ layout: 'closing', title: String(s.closing) })
- if (!list.length) list.push({ layout: 'cover', title: s.title || '未命名课件' })
- const media = [] // { name, buf, ext }
- const slideParts = []
- list.forEach((slide, idx) => {
- const layout = String(slide.layout || (slide.image ? 'image' : 'bullets'))
- const shapes = []
- const rels = []
- let ridCursor = 2 // rId1 给 slideLayout
- let shapeId = 2
- const pageNo = (color) => {
- shapes.push(shapeText(shapeId++, '页码', SLIDE_W - MARGIN - 900000, SLIDE_H - 500000, 900000, 300000,
- [{ text: `${idx + 1} / ${list.length}`, size: 1000, color: color || '9CA3AF', align: 'r' }]))
- }
- if (layout === 'cover') {
- shapes.push(shapeRect(shapeId++, '顶部色带', 0, 0, SLIDE_W, 152400, accent))
- shapes.push(shapeText(shapeId++, '主标题', MARGIN, 2011680, SLIDE_W - MARGIN * 2, 1600000,
- [{ text: slide.title || '未命名课件', size: 4400, bold: true, color: '1F2937' }], { anchor: 'b' }))
- if (slide.subtitle) {
- shapes.push(shapeText(shapeId++, '副标题', MARGIN, 3760000, SLIDE_W - MARGIN * 2, 900000,
- [{ text: slide.subtitle, size: 2000, color: '475569' }]))
- }
- shapes.push(shapeRect(shapeId++, '强调线', MARGIN, 3620000, 640080, 45720, accent))
- if (slide.meta) {
- shapes.push(shapeText(shapeId++, '署名', MARGIN, SLIDE_H - 1100000, SLIDE_W - MARGIN * 2, 400000,
- [{ text: slide.meta, size: 1300, color: '94A3B8' }]))
- }
- } else if (layout === 'section') {
- shapes.push(shapeRect(shapeId++, '章节底色', 0, 0, SLIDE_W, SLIDE_H, accent))
- shapes.push(shapeText(shapeId++, '章节标题', MARGIN, 2400000, SLIDE_W - MARGIN * 2, 1400000,
- [{ text: slide.title || '', size: 4000, bold: true, color: 'FFFFFF' }], { anchor: 'b' }))
- if (slide.subtitle) {
- shapes.push(shapeText(shapeId++, '章节说明', MARGIN, 3960000, SLIDE_W - MARGIN * 2, 800000,
- [{ text: slide.subtitle, size: 1800, color: 'E2E8F0' }]))
- }
- } else if (layout === 'closing') {
- shapes.push(shapeRect(shapeId++, '底色', 0, 0, SLIDE_W, SLIDE_H, 'F8FAFC'))
- shapes.push(shapeText(shapeId++, '结语', MARGIN, 2560320, SLIDE_W - MARGIN * 2, 1400000,
- [{ text: slide.title || '谢谢', size: 4000, bold: true, color: accent, align: 'ctr' }], { anchor: 'b' }))
- } else {
- // 内容页(要点 / 图文):标题 + 色条 + 正文
- const hasImage = !!slide.image
- shapes.push(shapeRect(shapeId++, '标题色块', MARGIN, 660000, 68580, 609600, accent))
- shapes.push(shapeText(shapeId++, '标题', MARGIN + 228600, 610000, SLIDE_W - MARGIN * 2 - 228600, 700000,
- [{ text: slide.title || '', size: 2800, bold: true, color: '1F2937' }], { anchor: 'ctr' }))
- const bullets = Array.isArray(slide.bullets)
- ? slide.bullets.map((b) => (typeof b === 'string' ? { text: b } : { text: b.text, level: b.level || 0 }))
- : (slide.text ? String(slide.text).split('\n').filter(Boolean).map((t) => ({ text: t })) : [])
- const bodyW = hasImage ? 4937760 : SLIDE_W - MARGIN * 2
- const bodyH = SLIDE_H - 1900000 - 500000
- const count = bullets.length || 1
- const size = count <= 3 ? 2400 : count <= 5 ? 2000 : count <= 7 ? 1800 : 1600
- if (bullets.length) {
- shapes.push(shapeText(shapeId++, '正文', MARGIN, 1800000, bodyW, bodyH,
- bullets.map((b, i) => ({
- text: b.text,
- size: b.level ? Math.max(1400, size - 200) : size,
- bullet: !b.level,
- color: '334155',
- spaceBefore: i === 0 ? 0 : 1200
- }))))
- }
- if (hasImage) {
- const imgPath = path.resolve(String(slide.image))
- let buf = null
- try { buf = fs.readFileSync(imgPath) } catch { buf = null }
- if (buf && buf.length) {
- let ext = path.extname(imgPath).toLowerCase().replace('.', '')
- if (ext === 'jpeg') ext = 'jpg'
- if (!['png', 'jpg', 'gif'].includes(ext)) ext = 'png'
- const imgSize = imageSize(buf)
- const name = `image${media.length + 1}.${ext}`
- media.push({ name, buf, ext })
- const boxW = 4876800
- const boxH = 4114800
- const box = fitBox(imgSize ? imgSize.w : 16, imgSize ? imgSize.h : 9, boxW, boxH)
- const boxX = SLIDE_W - MARGIN - boxW
- const boxY = 1800000
- shapes.push(shapeRect(shapeId++, '图片底板', boxX, boxY, boxW, boxH, 'F1F5F9'))
- const rid = `rId${ridCursor++}`
- rels.push([rid, `../media/${name}`])
- shapes.push(shapePic(shapeId++, '配图', rid, boxX + box.x, boxY + box.y, box.w, box.h))
- }
- }
- if (slide.note) {
- shapes.push(shapeText(shapeId++, '备注行', MARGIN, SLIDE_H - 900000, SLIDE_W - MARGIN * 2, 340000,
- [{ text: slide.note, size: 1200, color: '64748B' }]))
- }
- if (footer) {
- shapes.push(shapeText(shapeId++, '页脚', MARGIN, SLIDE_H - 500000, SLIDE_W / 2, 280000,
- [{ text: footer, size: 1000, color: 'B0B7C3' }]))
- }
- pageNo()
- }
- slideParts.push({ xml: slideWrap(shapes.join('')), rels })
- })
- const slideOverrides = slideParts.map((_p, i) =>
- `<Override PartName="/ppt/slides/slide${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>`).join('')
- const mediaDefaults = []
- const seenExt = new Set()
- for (const m of media) {
- if (seenExt.has(m.ext)) continue
- seenExt.add(m.ext)
- const type = m.ext === 'png' ? 'image/png' : m.ext === 'jpg' ? 'image/jpeg' : 'image/gif'
- mediaDefaults.push(`<Default Extension="${m.ext}" ContentType="${type}"/>`)
- }
- const types = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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"/>
- ${mediaDefaults.join('')}
- <Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/>
- <Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/>
- <Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/>
- <Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>
- ${slideOverrides}
- </Types>`
- const presentation = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <p:presentation ${PPT_NS} saveSubsetFonts="1">
- <p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst>
- <p:sldIdLst>${slideParts.map((_p, i) => `<p:sldId id="${256 + i}" r:id="rId${i + 2}"/>`).join('')}</p:sldIdLst>
- <p:sldSz cx="${SLIDE_W}" cy="${SLIDE_H}"/><p:notesSz cx="6858000" cy="9144000"/>
- </p:presentation>`
- const presRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
- <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/>
- ${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('')}
- </Relationships>`
- const rootRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
- <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/>
- </Relationships>`
- const masterRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
- <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>
- <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>
- </Relationships>`
- const layoutRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
- <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="../slideMasters/slideMaster1.xml"/>
- </Relationships>`
- const entries = [
- ['[Content_Types].xml', types],
- ['_rels/.rels', rootRels],
- ['ppt/presentation.xml', presentation],
- ['ppt/_rels/presentation.xml.rels', presRels],
- ['ppt/slideMasters/slideMaster1.xml', pptMaster()],
- ['ppt/slideMasters/_rels/slideMaster1.xml.rels', masterRels],
- ['ppt/slideLayouts/slideLayout1.xml', pptLayout()],
- ['ppt/slideLayouts/_rels/slideLayout1.xml.rels', layoutRels],
- ['ppt/theme/theme1.xml', pptTheme(accent)]
- ]
- slideParts.forEach((p, i) => {
- entries.push([`ppt/slides/slide${i + 1}.xml`, p.xml])
- const rels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
- <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>
- ${p.rels.map(([rid, target]) => `<Relationship Id="${rid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="${target}"/>`).join('')}
- </Relationships>`
- entries.push([`ppt/slides/_rels/slide${i + 1}.xml.rels`, rels])
- })
- for (const m of media) entries.push([`ppt/media/${m.name}`, m.buf])
- return { buf: zip(entries), slideCount: slideParts.length }
- }
- export function writePptx (file, spec) {
- const built = buildPptx(spec)
- const out = path.resolve(file)
- fs.mkdirSync(path.dirname(out), { recursive: true })
- fs.writeFileSync(out, built.buf)
- return { file: out, bytes: built.buf.length, slideCount: built.slideCount }
- }
|