/**
* 本地 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, '"')
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*/>|`, 'g')
let m
while ((m = tokenRe.exec(block))) {
if (m[1] !== undefined) line += XUNESC(m[1])
else if (m[0].startsWith('[\s\S]*?<\/w:tbl>/g
let t
while ((t = tblRe.exec(xml))) {
const rows = []
const rowRe = /][\s\S]*?<\/w:tr>/g
let r
while ((r = rowRe.exec(t[0]))) {
const cells = []
const cellRe = /[\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 = /([\s\S]*?)<\/si>/g
let m
while ((m = re.exec(sst.toString('utf8')))) {
const texts = [...m[1].matchAll(/]*)?>([\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(/]*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 = /]*>([\s\S]*?)<\/row>/g
let rm
while ((rm = rowRe.exec(xml))) {
const cells = []
const cellRe = /]*)>([\s\S]*?)<\/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(/]*)?>([\s\S]*?)<\/t>/g)].map((x) => XUNESC(x[1])).join('')
} else {
const v = (inner.match(/([\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(/[\s\S]*?<\/a:p>/g) || []) {
const line = [...p.matchAll(/]*)?>([\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 = /\/(?[A-Za-z0-9#+._-]+)\s+[-\d.]+\s+Tf|\((?(?:\\.|[^\\()])*)\)\s*Tj|\[(?(?:[^\]\\]|\\.)*)\]\s*TJ|<(?[0-9A-Fa-f\s]+)>\s*Tj|(?-?[\d.]+)\s+(?-?[\d.]+)\s+(?:Td|TD)|(?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 ? `` : ''
const runs = String(text).split('\n').map((line) => `${XESC(line)}`).join('')
return `${pPr}${runs}`
}
const TABLE = (rows) => {
const border = 'w:val="single" w:sz="4" w:space="0" w:color="999999"'
const borders = ``
const body = rows.map((cells, ri) => `${cells.map((c) => `${PARA(c, ri === 0 ? 'TableHead' : '')}`).join('')}`).join('')
return `${borders}${body}`
}
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('')
else body.push(PARA(b.text || ''))
}
if (!body.length) body.push(PARA(''))
const documentXml = `
${body.join('')}`
const stylesXml = `
`
const types = `
`
const rels = `
`
const docRels = `
`
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 `${v}`
if (v === null || v === undefined || v === '') return ''
return `${XESC(v)}`
}).join('')
return `${tds}
`
}).join('')
return `
${body}`
}
const workbook = `
${list.map((s, i) => ``).join('')}`
const wbRels = `
${list.map((_s, i) => ``).join('')}`
const types = `
${list.map((_s, i) => ``).join('')}`
const rels = `
`
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 = '' +
''
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 `
`
}
function pptMaster () {
return `
${SPRITE_HEAD}
`
}
function pptLayout () {
return `
${SPRITE_HEAD}
`
}
function shapeRect (id, name, x, y, cx, cy, fill, { rounded = false } = {}) {
return `
`
}
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
? ''
: ''
const indent = p.bullet ? ' marL="352425" indent="-352425"' : ''
const before = p.spaceBefore ? `` : ''
const after = p.spaceAfter ? `` : ''
const props = `` +
`` +
``
const text = XESC(p.text == null ? '' : p.text)
const run = p.text === '' ? '' : `${props}${text}`
const end = ``
return `${before}${after}${bullet}${run || ' '}${end}`
}).join('')
return `
${body}`
}
function shapePic (id, name, rid, x, y, cx, cy) {
return `
`
}
/** 图片在框内等比缩放并居中(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) => `
${SPRITE_HEAD}${shapes}
`
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) =>
``).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(``)
}
const types = `
${mediaDefaults.join('')}
${slideOverrides}
`
const presentation = `
${slideParts.map((_p, i) => ``).join('')}
`
const presRels = `
${slideParts.map((_p, i) => ``).join('')}
`
const rootRels = `
`
const masterRels = `
`
const layoutRels = `
`
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 = `
${p.rels.map(([rid, target]) => ``).join('')}
`
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 }
}