pdf2ofd
v1.0.1
Published
PDF → OFD 转换器。纯 Node 实现,零运行时依赖(pdf.js 作为 peerDependency),保留可搜索文字、内嵌子集字体与位图,输出符合 GB/T 33190 的 OFD 包。
Maintainers
Readme
pdf2ofd — PDF → OFD 转换
成熟度提示(beta):本模块处于 beta 阶段。转换结果可用于预览与一般流转,版面、文字、内嵌字体、图像、渐变与线型均已对齐,但不保证与 PDF 原件逐像素一致,也不支持表单域、注释与Type3 字体。API 与行为可能随版本演进而调整。用于正式归档、合同、票据等场景前,请务必人工核对输出文件。
概述
把 PDF 转成符合 GB/T 33190(电子文件存储与交换格式·版式文档)的 OFD 包,保留可搜索文字、内嵌子集字体与位图,图表以矢量路径、渐变填充与虚线线型表达。
- 解析:用 pdf.js(
pdfjs-dist的 ESM 版本)读取 PDF,拿到每页的绘制指令流与文本层 - 映射:矢量路径 →
PathObject,文本 →TextObject,图像 →ImageObject+ PNG 资源,Form XObject → 内联展开为页面级图元 - 打包:生成
OFD.xml/Document.xml/PublicRes.xml/DocumentRes.xml/ 各页Content.xml,用 ZIP(deflate)封装
产物可被 ofd.js 直接回读渲染,也可在 WPS、数科等第三方 OFD 阅读器打开。
两种用法
一、npm 包(推荐)
npm install pdf2ofd pdfjs-distpdfjs-dist 是 peerDependency(≥ 4),需单独安装 —— 它负责解析 PDF,本包只做 OFD 侧的输出。本包自身零运行时依赖。
仓库内自行组装:
npm run build:pdf2ofd # 转换器产物 → build/pdf2ofd/(pdf2ofd.js / pdf2ofd.min.js)
npm run build:zips # 三个模块各自打 zip → dist/<版本>/,含 pdf2ofd.zip
npm run build:pdf2ofd-npm # npm 包 → dist/<版本>/pdf2ofd/二、源码树直接跑
node build/pdf2ofd/pdf2ofd.js input.pdf # 输出 input.ofd
node build/pdf2ofd/pdf2ofd.js input.pdf output.ofd # 指定输出路径命令行
npm 包提供的 pdf2ofd 命令:
pdf2ofd input.pdf # 输出 input.ofd
pdf2ofd input.pdf out/result.ofd # 指定输出
pdf2ofd -q input.pdf out.ofd # 静默
pdf2ofd --help进度与统计信息走 stderr,转换正常时输出:
已处理 14/14 页
完成:out/result.ofd(14 页,24 字体,90 图像,875598 字节)代码调用
const { convert } = require('pdf2ofd');
const stats = await convert('input.pdf', 'output.ofd', {
onProgress: (done, total) => console.log(`${done}/${total}`),
quiet: true, // 静默,不打印进度与统计
});
// stats = { pages, fonts, images, bytes }ofdPath 省略时与输入同名(.pdf → .ofd)。
批量:
const { convertMany } = require('pdf2ofd');
// 顺序执行,避免大文件并发吃满内存
await convertMany(['a.pdf', 'b.pdf'], { quiet: true });
// 也可逐项指定输出与选项
await convertMany([
{ from: 'a.pdf', to: 'out/a.ofd' },
{ from: 'b.pdf', options: { quiet: true } },
]);导出成员
| 成员 | 说明 |
| --- | --- |
| convert(pdfPath, ofdPath?, options?) | 主转换函数,返回统计对象 |
| convertMany(list, options?) | 批量转换,顺序执行,返回统计对象数组 |
| ZipWriter | 最小 ZIP 写入器(deflate),add(name, data) + build() |
| encodePng(width, height, rgba) | RGBA → PNG 字节 |
| PT_TO_MM | 点到毫米换算系数 25.4/72 |
| version | 包版本号 |
options 只支持两个字段:onProgress(done, total) 与 quiet。没有 cMapUrl / maxPages / imageWaitMs / defaultFont 等参数 —— pdf.js 的资源路径由包内按 require.resolve('pdfjs-dist/…') 自行解析,不依赖调用方传路径。
环境要求
- Node.js 18+(用到
fs/zlib/ ESM 动态import()) - pdfjs-dist ≥ 4(源码树里已在
devDependencies,npm 包里是 peerDependency)
本模块仅在 Node 环境运行。早期版本做过浏览器双端支持(rt 运行时适配层 + Buffer polyfill),已按需求移除 —— 浏览器缺少 zlib,PNG 的 IDAT 只能退化成zlib 存储模式(体积膨胀十余倍),维护成本高于收益。
产物结构
OFD.xml 文档根(DocID / 创建时间 / DocRoot)
Doc_0/Document.xml 页面清单 + PublicRes / DocumentRes 引用
Doc_0/PublicRes.xml 字体声明(ofd:Font → FontFile)
Doc_0/DocumentRes.xml 图像声明(ofd:MultiMedia)
Doc_0/Res/font_<id>_<id>.otf|ttf 内嵌字体二进制
Doc_0/Res/image_<id>.png 图像资源
Doc_0/Pages/Page_<n>/Content.xml 各页图元DocumentRes.xml 里没有 CompositeGraphicUnits —— 见下文「复合图形单元」。
实现要点
以下几处是踩过坑后定下的实现,改动前请先读代码注释。
坐标与单位
1pt = 25.4/72 mm;PDF Y 轴向上、OFD Y 轴向下。
图元坐标保留 PDF 用户空间原值,把「CTM + pt→mm + Y 轴翻转」整体交给 OFD 的 CTM 属性表达,而不是在生成路径点时把矩阵烘焙进去。旋转 / 斜切 / 镜像因此不会丢失 —— 烘焙后的坐标只能表达平移+缩放。
渲染器按「Boundary 原点 + CTM(坐标)」定位,所以坐标要先归一化:令 (dx,dy) = L⁻¹·(T − B0),输出 (x+dx, y+dy),则任意仿射变换下落点都严格等于 L(x,y)+T。
线宽与虚线:绝不预先乘 CTM
OFD 的 LineWidth 与 DashPattern 都和 AbbreviatedData 同处一个坐标空间,渲染时会被 CTM 再缩放一次。
所以这两个属性必须写 PDF 用户空间原值(如 1 / 2 / 3 / 5),不能预先乘 CTM 的 mm 缩放系数。旧实现乘了,等于把线宽缩小了近 3 倍(0.3528 因子 × 图表内 0.35~0.47 的 CTM),所有线细成同一条 —— 正是「连线有些粗有些细、现在一样细」的根因。
DashPattern 在 OFD 规范里是 PathObject 的属性(DashPattern="4 4"),不是子元素。写成子元素引擎会忽略,虚线椭圆全部退化成实线。
唯一的例外:坐标被 absorbScale() 乘过 k 时,同一空间的线宽与虚线也要跟着乘 k。
极小 CTM:把缩放吸收进坐标
fmt() 只保留 4 位小数,而图表里 CTM 缩放过小是常态 —— 第 11 页坐标轴的 CTM 缩放只有 7.638e-5(PDF 用 transform 把线框坐标放大了一万三千倍),直接被写成 0,CTM 输出成 0 0 0 0 0 0,路径全部塌缩到一点,整片坐标轴消失。
对策(与数科产物一致):缩放过小时不再依赖 CTM 表达缩放,而是把缩放吸收进图元坐标,CTM退化为单位阵。效果是坐标从 322739 变成 ~24.6、CTM 从 0 变成 0.3528,数值落在 fmt() 的有效精度内。
阈值 CTM_TINY = 0.05。注意 geom() 必须收缩放后的点,否则 Boundary 会被算成天文数字(6446519),CTM 又退化成 1 0 0 1。
裁剪:pdf.js 的 clip 是延迟一位消费的
pdf.js 的 clip() / eoClip() 只置位 pendingClip,真正建立裁剪区是在下一个 constructPath 被 consumePath() 消费时。
所以转换器里也延迟一位:clip 只置位 pendingClipMode,随后那条 constructPath(endPath) 才拿来登记裁剪区。旧实现相反 —— clip 到达时立刻消费 pendingPath,那是上一条已用掉的陈旧路径,于是裁剪区整体错位,把图例色块之类的小图元误剔(第 10/13 页图表标签前的颜色标识就是这样消失的:色块实际在 clip 区外侧约 1mm)。
还有一条不能二选一的规则:一条 endPath 可能既是裁剪区又是填充区。PDF 里 W n 之后紧跟 sh f 是常见写法(先裁剪、再用同一形状填渐变)。所以 clip 分支里只能 clipBoxes.push(),绝不能清掉 pendingPath —— 清了之后紧随其后的 shadingFill 拿不到区域,81 根渐变柱会被静默丢弃。
渐变:必须先 await 预取
渐变以 OFD 轴向渐变表达:
<ofd:FillColor>
<ofd:AxialShd Extend="3" StartPoint="x0 y0" EndPoint="x1 y1">
<ofd:Segment Position="0"><ofd:Color Value="155 193 255"/></ofd:Segment>
<ofd:Segment Position="1"><ofd:Color Value="63 128 205"/></ofd:Segment>
</ofd:AxialShd>
</ofd:FillColor>page.objs.get(id) 对未解析对象返回的是 Promise,不能同步取用。任何按 id 取对象的逻辑(渐变、图案)都必须先 await 预解析。
prefetchGradients() 会在进入操作符循环前扫一遍 fnArray,把所有 shadingFill 引用的 pattern id 收集起来 await 完,存进 gradShades 缓存。旧实现直接在 shadingFill 里同步 objs.get(patId),抛错落进 catch → 返回兜底色 0.5 → 表现为 FillColor 默认 0 0 0纯黑。
径向渐变按轴向近似(OFD 有对应规范但兼容性未验证)。
平铺图案(TilingPattern):只取平均色,不还原纹理
setFillColorN / setStrokeColorN 的参数不一定是普通颜色——第 13 页的灰度网点就是一张 TilingPattern。patternImageId() 从 [ 'TilingPattern', backdrop, { fnArray, argsArray }, matrix, bbox ] 里挖出图案内联图片的 objId,prefetchPatternColors() 与 prefetchGradients() 一起在算子循环之前预取(同样因为 page.objs.get() 是异步的),解码每张图案图一次并求平均 RGB 存进 patternColors;填充/描边色随后替换成这个平均色,区域明暗与原件一致。
只保留平均色调,不表达平铺纹理(OFD 里没有 WPS 能稳定渲染的对应写法)。其余 ...ColorN 色彩空间(Indexed / CMYK / Lab)仍不支持,策略是保持上一个颜色,而不是塌成纯黑。
复合图形单元:本转换器不输出
Form XObject 一律内联展开为页面级 PathObject / ImageObject(语义等价于 save + concat(matrix) … restore),不收进 DocumentRes 的 <ofd:CompositeGraphicUnit>,页面也不用 <ofd:CompositeObject> 引用。
原因:引擎不识别 CompositeObject 时整个图表会消失(实测第 6 页)。数科基准产物里 CompositeObject 只用于个别分组,页面 Content.xml 直接包含数百个 PathObject / ImageObject;本项目因WPS 裁没内容的历史踩坑,同样采取「不引入」策略。
产物实测:CompositeGraphicUnits 0 处、CompositeObject 0 处。改代码时不要依据旧版本文档的说法反着来。
Form 内部常含「远大于自身」的背景块(如 1152×2199 的整页白底)。按 PDF 语义它被限制在 Form 的 BBox 内,所以 paintFormXObjectBegin 会把 BBox 登记进 clipBoxes,供剔除与丢弃使用,但不输出 <ofd:Clips>(见下)。
页面层不输出 <ofd:Clips>
两次实测都证明:在页面层发 Clips 会让 WPS 把内容整块裁没(2026-10-13 停发后第 10/11/13 页图表正常;同日尝试恢复,第 9/10/12 页图表又全部消失)。
所以采取「只剔除、不表达」的保守策略:
clipBoxes的包围盒用于剔除裁剪区外的图元isOversizedRect()对「比可见区域大出 1.8 倍以上的纯矩形填充块」直接丢弃
为什么不把超大块收敛成可见区域大小的矩形:那样会在图注文字之后留下一小块底色板,照样把图注盖住 —— 第 6 页就是这么丢的。丢弃的代价只是少了底色,而底色本来就是白的。isOversizedRect() 仅对纯矩形生效,曲线/折线图元保持原样,避免把图表裁坏。
可见性判定的两种模式
visible(box, mode) 的 mode 决定用哪种可见区域:
'page'(文字 / 描边线)→ 只用页面范围,完全不受clipBoxes影响'clip'(填充块)→ 按裁剪区求交,这才是 PDF 语义要求的
为什么描边线也要豁免裁剪区:表格框线横跨整行/整列,往往在「单元格裁剪区建立之前」就已发出,或跨越多个裁剪区。实测某签名板文档第 2 页 12 条表格框线(box=[29.8, 25.5, 150.5, 0],横跨 150mm 整行宽)里有 10 条被单元格 eoClip 剔掉。容差 CLIP_EPS = 0.6:贴着裁剪边界的图框线/ 图注不误杀,页外上千毫米的垃圾路径仍会清掉。
字体嵌入
从 worker 消息层(doc._transport.messageHandler.comObj)拦截 pdf.js 编译后的子集字体字节,随文档嵌入 PublicRes。
三个必须注意的点:
- 非嵌入字体也必须写进
PublicRes。Helvetica 等 14 种标准字体在消息里mimetype=null、无data,若被if (!f) continue跳过,会出现「有 1064 个文字对象但PublicRes里 0 个字体」,严格渲染器会显示异常。 - 同名不同 Font ID 要各自独立注册。一份 PDF 里
Calibri可能有 3 个 Font ID(子集不同、cmap 大小不同)。viewer 侧按ofdf_<id>_<name>生成 family 区分,只用fontName做 key 会导致只有第一个注册成功、其余静默回退系统字体。 ensureMacCmap()给内嵌字体补 Mac(platform 1/0) cmap 子表。pdf.js 编译出的子集字体常只带 Windows(3/1) format-4 cmap,部分查看器优先读 Mac 表,故补上以提升兼容性。注意:这并不能单独修好 WPS 图表标签乱码 —— 用无 ToUnicode 子集字体画的标签带的是私有区假码(0x21…),任何 cmap 子表都还原不出真实文字,需要重映射标签文本本身。
图像
page.objs 只有 get / has,图像数据在 getOperatorList() 之后异步送达。故 waitImages() 先扫 ops 收集 paintImageXObject 引用的 objId,再以 20ms 间隔轮询,上限 8 秒。
imageToRgba() 按 img.kind 分派:1=灰度、2=RGB、3=RGBA(旧实现只认 3,RGB/灰度图会被整块丢弃),统一转成 RGBA 后由 encodePng() 编成 PNG。
编码时逐行拷贝用
raw.set(rgba.subarray(...)),不要改回Buffer.from(buffer, off, len).copy()—— 三参数重载的边界行为曾导致每行像素都写成第 0 行,而 PNG 的签名/尺寸/CRC 全部校验通过,极难察觉。
文本
文字取自操作符列表里 showText 的字形(每个字形自带 Unicode 与宽度),不用 getTextContent()。填充色与字号取自 showText 处的图形/文字状态。
TextCode 的坐标 / DeltaX / Size 统一用字号空间(1 单位 = 1/Size em),字形包围盒同理。
Glyphs 数组长度必须严格等于 DeltaX 项数 + 1(对齐数科产物,实测 2175 个 TextObject 无一例外):末位字形是真实字形,但它的 DeltaX 不单独给出,由渲染器自行推进。codeList 与 Glyphs 保持严格 1:1。
PNG 编码
纯 JS 手写(IHDR / IDAT / IEND + CRC32),走 Node zlib.deflateSync({level:9})。
实测数据
以 test/ 下保留的那份 14 页论文 PDF(US Letter,正文 + 矢量图表 + 9 种子集字体)为基线:
node build/pdf2ofd/pdf2ofd.js test/<你的样本>.pdf
# 已处理 14/14 页
# 完成:test/<你的样本>.ofd(14 页,24 字体,90 图像,875598 字节)与数科(商业转换器)对同一份 PDF 的产物对齐情况:
| 检查项 | 数科 | 本转换器 |
| --- | --- | --- |
| 第 2 页虚线路径 | 5 | 7(同源,多出2 条同参数副本) |
| 第 6 页线宽档位 | 1 / 2 / 3 / 5 | 1 / 2 / 3 / 5 ✓ |
| 第 7 页线宽档位 | 1 / 2 / 3 / 5 / 8 | 1 / 2 / 3 / 4 / 5 / 8 ✓ |
| 第 10 页图例色块 | 有 | 灰 / 深灰 2 色 ✓ |
| 第 11 页 CTM 全零路径 | 0 | 0 ✓ |
| 第 11 页 AxialShd | 162 | 162 ✓ |
| 第 11 页渐变柱 | 81 | 81 ✓ |
| 第 13 页灰度网点 | TilingPattern 纹理 | 平铺灰(只保留图案平均色) |
已知未对齐项:数科把每个图形拆成独立 CompositeGraphicUnit(226 个 Unit,其中 96 个为空)靠裁剪隔离;本转换器全部平铺在页面层且不输出裁剪,因此曲线会溢出到相邻图形。另外数科全文档只保留 22 条骨架线(线宽集中在 0.75 / 2 / 3),丢弃了 PDF 的 190 条描边。这两点已确认不再跟进。
资源与安全
本转换器会解析外部 PDF 文件。
- 内存:单页操作符列表、图像解码结果、渐变预取表都在内存中。数百页的高分辨率扫描件可能占用可观内存(实测 14 页论文样本峰值约 200 MB)。
- 图像等待上限 8 秒:
waitImages()轮询 pdf.js 异步送达的图像数据,超过 8 秒按「已就绪」处理(缺失图像会被跳过,不报错)。极端情况下可能出现图像缺失但不告警。 - 不验证 PDF 自身签名。输入 PDF 若带数字签名,本工具不校验签名有效性,只做内容转换。
- pdf.js 解析层的安全防护由 pdfjs-dist 负责,本工具不做额外加固。若需处理不可信来源的 PDF,建议在受限环境(容器 / 低权限进程)中运行。
已知限制
- 不支持:表单域、注释、Type3 字体
- 径向渐变按轴向近似,未验证严格视觉一致性
- 平铺图案只取平均色:网点/纹理本身不还原;除图案内联图片外的
...ColorN色彩空间(Indexed / CMYK / Lab)保持上一个颜色 - 图像型PDF 体积会涨:pdf.js 给的是解码后像素,重编 PNG 通常比原 JPEG 大,扫描件尤其明显
- 文本间距近似:逐字
DeltaX均分总宽,长串拉丁文本可能有轻微字距偏移(中文等宽准确) - CropBox 偏移未特殊处理,页面尺寸取
page.view - Beta 阶段:API 与行为可能随版本演进而调整;未覆盖 PDF 全部特性,用于正式归档、合同、票据等场景前请人工核对输出文件
维护者注记
以下几项不会自动同步,发布前需手动处理:
| 项 | 位置 | 说明 |
| --- | --- | --- |
| npm 包版本号 | build/build-pdf2ofd-npm.js 的 PKG.version | 自动读取仓库根 package.json 的 version,与 dist/<版本>/ 目录保持一致 |
| npm 包名 | build/build-pdf2ofd-npm.js 的 PKG.name | pdf2ofd 在 npmjs 上已被占用时需改名 |
| 发行包的文件剥离 | build/common.js 的 distTransform() | 改了 web/viewer.html / web/viewer.js 的结构(选择器、事件、测试文件默认值)后,正则会失配。已加断言,构建会报错提示,不会静默发坏包 |
npm run build:pdf2ofd-npm 只重新组装 dist/<版本>/pdf2ofd/,不发布。发布是独立动作:
cd dist/<版本>/pdf2ofd
npm publish --access public排查指引
改完转换器后,跑一遍基准样本并核对统计数字(应为 14 页 / 24 字体 / 90 图像):
node build/pdf2ofd/pdf2ofd.js test/<你的样本>.pdf /tmp/chk.ofd产物完整性检查(ZIP 条目可解压 + CRC32、PNG chunk CRC、MultiMedia 声明数 == 图像条目数 == 各页 ImageObject 合计)可临时写脚本验证,注意三个易错点:
- ZIP 头是小端,PNG chunk 头是大端。混用会读出「条目数 0」的假象。
- 结构校验通过 ≠ 内容正确。PNG 的签名/尺寸/CRC/inflate 全过,像素内容仍可能完全错。涉及图像编码必须做逐字节像素比对。
- 只看「没有全零 CTM」不够。第 11 页颜色丢失那次,CTM 全零路径 0 条、描边路径 8 条都正常,但 81 根渐变柱被静默丢弃了。按图元类型分别计数(AxialShd 数、ImageObject 数、TextObject 数)才能定位。
排查显示问题时优先复用项目现成的 ofd/core/zip.js,别自己重写 ZIP 解析器。
六条通用规律
以下是本项目 PDF → OFD 转换反复验证过的规律,改动转换器时务必逐条对照:
LineWidth/DashPattern与AbbreviatedData同坐标空间,绝不预先乘 CTMDashPattern是PathObject的属性,不是子元素- pdf.js 的 clip 延迟一位消费,
clip本身不携带路径 fmt()的 4 位小数对极小 CTM 是致命的;缩放过小时应把缩放吸收进坐标page.objs.get()任何按 id 取对象都必须先await预取- 一条
endPath可能同时是 clip 区与填充区,两者不能二选一
pdf2ofd — PDF → OFD Converter
Maturity notice (beta): this module is in beta. Converted output is fine for preview and general circulation — layout, text, embedded fonts, images, gradients and stroke styles are all aligned — but it is not guaranteed to be pixel-identical to the source PDF, and form fields, annotations and Type3 fonts are not supported. The API and behavior may change as it evolves. Before using it for formal archiving, contracts, invoices, or similar scenarios, manually verify the output file.
Overview
Converts a PDF into an OFD package conforming to GB/T 33190 (electronic document storage and exchange — layout documents), preserving searchable text, embedded subset fonts and bitmaps, with charts expressed as vector paths, gradient fills and dashed strokes.
- Parse: pdf.js (the ESM build from
pdfjs-dist) reads the PDF and exposes per-page drawing operators plus the text layer - Map: vector paths →
PathObject, text →TextObject, images →ImageObject+ PNG resources, Form XObjects → inlined as page-level graphics - Package: emits
OFD.xml/Document.xml/PublicRes.xml/DocumentRes.xml/ per-pageContent.xmland zips them (deflate)
The result is re-readable by ofd.js and opens in WPS and other third-party OFD viewers.
Two ways to use it
1. The npm package (recommended)
npm install pdf2ofd pdfjs-distpdfjs-dist is a peerDependency (≥ 4) and must be installed separately — it does the PDF parsing, this package only emits OFD. The package itself has zero runtime dependencies.
To assemble it from this repository:
npm run build:pdf2ofd # converter artifacts → build/pdf2ofd/ (pdf2ofd.js / pdf2ofd.min.js)
npm run build:zips # all three module zips → dist/<version>/, incl. pdf2ofd.zip
npm run build:pdf2ofd-npm # npm package → dist/<version>/pdf2ofd/2. Run from the source tree
node build/pdf2ofd/pdf2ofd.js input.pdf# writes input.ofd
node build/pdf2ofd/pdf2ofd.js input.pdf output.ofd # explicit output pathCLI
The pdf2ofd command shipped with the npm package:
pdf2ofd input.pdf # writes input.ofd
pdf2ofd input.pdf out/result.ofd # explicit output
pdf2ofd -q input.pdf out.ofd # quiet
pdf2ofd --helpProgress and statistics go to stderr:
已处理 14/14 页
完成:out/result.ofd(14 页,24 字体,90 图像,875598 字节)From code
const { convert } = require('pdf2ofd');
const stats = await convert('input.pdf', 'output.ofd', {
onProgress: (done, total) => console.log(`${done}/${total}`),
quiet: true, // suppress progress and summary output
});
// stats = { pages, fonts, images, bytes }ofdPath may be omitted, in which case it matches the input name (.pdf → .ofd).
Batch conversion:
const { convertMany } = require('pdf2ofd');
// Sequential, so large files don't blow up memory by running concurrently
await convertMany(['a.pdf', 'b.pdf'], { quiet: true });
// Per-item output path and options are also supported
await convertMany([
{ from: 'a.pdf', to: 'out/a.ofd' },
{ from: 'b.pdf', options: { quiet: true } },
]);Exports
| Member | Description |
| --- | --- |
| convert(pdfPath, ofdPath?, options?) | Main entry, returns the stats object |
| convertMany(list, options?) | Batch conversion, sequential, returns an array of stats objects |
| ZipWriter | Minimal ZIP writer (deflate): add(name, data) + build() |
| encodePng(width, height, rgba) | RGBA → PNG bytes |
| PT_TO_MM | Point-to-millimetre factor 25.4/72 |
| version | Package version |
options accepts exactly two fields: onProgress(done, total) and quiet. There are no cMapUrl / maxPages / imageWaitMs / defaultFont parameters — pdf.js resource paths are resolved by the package itself via require.resolve('pdfjs-dist/…'), so callers never pass paths.
Requirements
- Node.js 18+ (uses
fs,zlib, and dynamic ESMimport()) - pdfjs-dist ≥ 4 (already in
devDependenciesin the source tree; a peerDependency for the npm package)
This module runs in Node only. An earlier version supported browsers too (a rt runtime adapter layer plus a Buffer polyfill), but that was removed: without zlib the browser path degrades PNG IDAT to zlib stored blocks — roughly 11× larger — and the maintenance cost outweighed the benefit.
Output layout
OFD.xml document root (DocID / dates / DocRoot)
Doc_0/Document.xml page list + PublicRes / DocumentRes references
Doc_0/PublicRes.xml font declarations (ofd:Font → FontFile)
Doc_0/DocumentRes.xml image declarations (ofd:MultiMedia)
Doc_0/Res/font_<id>_<id>.otf|ttf embedded font binaries
Doc_0/Res/image_<id>.png image resources
Doc_0/Pages/Page_<n>/Content.xml per-page graphicsThere is no CompositeGraphicUnits in DocumentRes.xml — see "Composite graphic units" below.
Implementation notes
These are decisions made after hitting real problems. Read the in-file comments before changing any of them.
Coordinates and units
1pt = 25.4/72 mm; PDF's Y axis points up, OFD's points down.
Graphic coordinates keep the original PDF user-space values. The combined "CTM + pt→mm + Y flip" is expressed through OFD's CTM attribute rather than baked into path points — otherwise rotation, skew and mirroring are lost, because baked coordinates can only express translation plus scale.
Renderers position things as "Boundary origin + CTM(coords)", so coordinates must be normalised first: with (dx,dy) = L⁻¹·(T − B0), emitting (x+dx, y+dy) makes the landing point exactly L(x,y)+T for any affine transform.
Line width and dashes: never pre-multiply by the CTM
OFD's LineWidth and DashPattern live in the same coordinate space as AbbreviatedData and get scaled by the CTM again at render time.
So both attributes must carry the original PDF user-space value (e.g. 1 / 2 / 3 / 5) and must not be pre-multiplied by the CTM's mm scale. The old implementation did pre-multiply, shrinking line widths by nearly 3× (a 0.3528 factor times the 0.35~0.47 CTM inside charts) so every line collapsed to the same thin stroke — exactly the "some connections are thick, some thin, now they're all the same" symptom.
In the OFD spec DashPattern is a PathObject attribute (DashPattern="4 4"), not a child element. Writing it as a child makes engines ignore it, and every dashed ellipse degrades to a solid one.
The one exception: when coordinates were multiplied by k via absorbScale(), line width and dash lengths in that same space must be multiplied by k too.
Tiny CTMs: absorb the scale into the coordinates
fmt() keeps only 4 decimal places, and tiny CTM scales are common in charts — the page 11 axes have a CTM scale of just 7.638e-5 (the PDF uses a transform to blow the line-box coordinates up by thirteen thousand×). That gets written as 0, the CTM comes out as 0 0 0 0 0 0, every path collapses to a point and the whole axis system disappears.
The fix (matching the reference output): when the scale is too small, stop expressing it through the CTM and instead absorb the scale into the graphic coordinates, letting the CTM degenerate to the identity. Coordinates then go from 322739 to ~24.6 and the CTM from 0 to 0.3528 — numbers that land inside fmt()'s effective precision.
The threshold is CTM_TINY = 0.05. Note that geom() must receive the already-scaled points, or Boundary comes out astronomically large (6446519) and the CTM degenerates back to 1 0 0 1.
Clipping: pdf.js consumes clip one step late
pdf.js's clip() / eoClip() only set a flag on pendingClip; the clipping region is actually established when the next constructPath is consumed by consumePath().
So the converter delays by one too: clip only sets pendingClipMode, and the following constructPath(endPath) is what registers the clip box. The old implementation did the opposite — on clip it immediately consumed pendingPath, which is the previous, already-used stale path. The clip regions ended up shifted wholesale, wrongly culling small elements such as legend colour swatches (this is how the colour markers before the chart labels on pages 10/13 disappeared: the swatches sit roughly 1mm outside the clip region).
One more rule that is not either/or: a single endPath may be both a clip region and a fill region. W n followed by sh f is common in PDFs (clip first, then fill the same shape with a gradient). So the clip branch may only do clipBoxes.push() and must never clear pendingPath — doing so makes the immediately following shadingFill find no region and silently drop all 81 gradient bars.
Gradients: you must await the prefetch
Gradients are expressed as OFD axial shades:
<ofd:FillColor>
<ofd:AxialShd Extend="3" StartPoint="x0 y0" EndPoint="x1 y1">
<ofd:Segment Position="0"><ofd:Color Value="155 193 255"/></ofd:Segment>
<ofd:Segment Position="1"><ofd:Color Value="63 128 205"/></ofd:Segment>
</ofd:AxialShd>
</ofd:FillColor>page.objs.get(id) returns a Promise for objects that aren't resolved yet, so it cannot be used synchronously. Any id-keyed lookup (gradients, patterns) must await the prefetch first.
prefetchGradients() scans fnArray before entering the operator loop, collects every pattern id referenced by shadingFill, awaits them all and stores the result in a gradShades cache. The old implementation called objs.get(patId) synchronously inside shadingFill; the throw landed in the catch and returned a fallback colour of 0.5, which showed up as FillColor defaulting to pure black 0 0 0.
Radial gradients are approximated as axial (OFD has a corresponding spec but compatibility is unverified).
Tiling patterns: average colour, no texture
setFillColorN / setStrokeColorN are not plain colours — page 13's grey halftone screen is a TilingPattern. patternImageId() digs the pattern's inline image object id out of the [ 'TilingPattern', backdrop, { fnArray, argsArray }, matrix, bbox ] array, and prefetchPatternColors() — run alongside prefetchGradients() before the operator loop, for the same page.objs.get() async reason — decodes each such image once and stores its average RGB in patternColors. The fill/stroke colour is then replaced by that average, so the region renders in the right tone.
Only the average tone is kept: pattern tiling itself is not expressed (OFD has no direct equivalent that WPS renders reliably). Other ...ColorN colour spaces (Indexed / CMYK / Lab) stay unsupported — they keep the previous colour instead of collapsing to black.
Composite graphic units: not emitted
Form XObjects are always inlined as page-level PathObject / ImageObject (semantically equivalent to save + concat(matrix) … restore). They are not collected into <ofd:CompositeGraphicUnit> in DocumentRes, and the page does not reference them via <ofd:CompositeObject>.
Reason: when the engine fails to recognise CompositeObject, the entire chart vanishes (observed on page 6). In the reference output CompositeObject is only used for occasional grouping — the page Content.xml directly contains hundreds of PathObject / ImageObject. For the same reason this project (after WPS once clipped content away) takes the "don't introduce it" approach.
Measured on the output: 0 CompositeGraphicUnits, 0 CompositeObject. Do not work from older documentation that claims otherwise.
Form internals often contain background blocks far larger than the Form itself (e.g. a full-page 1152×2199 white canvas). PDF semantics constrain them to the Form's BBox, so paintFormXObjectBegin registers the BBox in clipBoxes for culling and dropping — but emits no <ofd:Clips> (see below).
No page-level <ofd:Clips>
Two separate experiments proved that emitting Clips at page level makes WPS clip content away wholesale (disabling it on 2026-10-13 restored charts on pages 10/11/13; re-enabling it the same day made charts on pages 9/10/12 vanish again).
Hence the conservative "cull, don't express" strategy:
clipBoxesbounding boxes cull graphics outside the clip regionsisOversizedRect()drops pure-rectangle fills more than 1.8× the visible area
Clamping an oversized block down to the visible rectangle was rejected: that leaves a small colour patch sitting on top of the figure caption and covers it anyway — which is exactly how page 6 broke. The cost of dropping is merely the background, which is white anyway and carries no information. isOversizedRect() applies to pure rectangles only, so curves and polylines pass through untouched.
Two visibility modes
visible(box, mode)'s mode selects which visible region applies:
'page'(text / stroked lines) → page bounds only, entirely unaffected byclipBoxes'clip'(fill blocks) → intersected with the clip regions, which is what PDF semantics require
Stroked lines are also exempt from clip regions because table borders span entire rows or columns and are often emitted before the cell clip region exists, or across several of them. On one signature-pad document, 10 of 12 table border lines on page 2 (box=[29.8, 25.5, 150.5, 0], spanning the full 150mm row width) were culled by cell eoClip. The tolerance is CLIP_EPS = 0.6: borders and captions hugging the clip boundary survive, while garbage paths thousands of millimetres outside the page are still cleared.
Font embedding
Font bytes are intercepted from the worker message layer (doc._transport.messageHandler.comObj) after pdf.js compiles the subsets, then embedded into PublicRes.
Three things that must not be broken:
- Non-embedded fonts must still be declared in
PublicRes. The 14 standard fonts (Helvetica etc.) arrive withmimetype=nulland nodata; anif (!f) continueguard used to skip them, leaving 1064 text objects but zero font declarations — strict renderers then misbehave. - Same name, different Font ID must register independently. One PDF can carry three
CalibriFont IDs with different subsets and different cmap sizes. The viewer generates families asofdf_<id>_<name>; keying on fontName alone registers only the first and silently falls back to system fonts for the rest. ensureMacCmap()adds a Mac (platform 1/0) cmap subtable. pdf.js subsets often ship only a Windows (3/1) format-4 cmap; some viewers read the Mac table preferentially, so it is added for broader compatibility. Note: this alone does not fully fix WPS chart-label garbling — labels drawn with subset fonts that lack a ToUnicode CMap carry private-use codes (0x21…) that no cmap subtable can recover; those need the label text itself to be remapped.
Images
page.objs only exposes get/has; image data arrives asynchronously after getOperatorList(). So waitImages() first scans the ops for objIds referenced by paintImageXObject, then polls every 20 ms with an 8-second ceiling.
imageToRgba() dispatches on img.kind: 1=grayscale, 2=RGB, 3=RGBA (the old implementation only handled 3, dropping RGB and grayscale images wholesale), normalising everything to RGBA before encodePng().
Row copying uses
raw.set(rgba.subarray(...)). Do not revert toBuffer.from(buffer, off, len).copy()— that three-argument overload once made every row replicate row 0, while PNG signature, dimensions and CRC all still validated. Nearly impossible to spot.
Text
Text comes from the showText glyphs in the operator list (each carries its own Unicode and width) — not from getTextContent(). Fill colour and font size are taken from the graphics/text state at the showText position.
TextCode coordinates, DeltaX and Size all work in font-size space (1 unit = 1/Size em); glyph bounding boxes likewise.
The Glyphs array length must equal DeltaX count + 1 exactly (matching the reference implementation — verified across 2175 TextObjects with no exceptions): the final glyph is real but its DeltaX is not given separately, and the renderer advances it. codeList stays strictly 1:1 with Glyphs.
PNG encoding
Hand-written in pure JS (IHDR / IDAT / IEND + CRC32) over Node's zlib.deflateSync({level:9}).
Measured results
Using the 14-page academic-paper PDF kept in test/ as the baseline (US Letter, mixed text/vector figures, 9 subset fonts):
node build/pdf2ofd/pdf2ofd.js test/<your-sample>.pdf
# 已处理 14/14 页
# 完成:test/<your-sample>.ofd(14 页,24 字体,90 图像,875598 字节)Alignment against the commercial converter's output for the same PDF:
| Check | Reference | This converter |
| --- | --- | --- |
| Page 2 dashed paths | 5 | 7 (same source, 2 extra duplicates) |
| Page 6 line-width tiers | 1 / 2 / 3 / 5 | 1 / 2 / 3 / 5 ✓ |
| Page 7 line-width tiers | 1 / 2 / 3 / 5 / 8 | 1 / 2 / 3 / 4 / 5 / 8 ✓ |
| Page 10 legend swatches | present | grey / dark grey, 2 colours ✓ |
| Page 11 all-zero CTM paths | 0 | 0 ✓ |
| Page 11 AxialShd | 162 | 162 ✓ |
| Page 11 gradient bars | 81 | 81 ✓ |
| Page 13 halftone screen | tiled TilingPattern texture | flat grey — only the pattern's average colour is kept |
Known unaligned items: the reference splits each graphic into its own CompositeGraphicUnit (226 units, 96 of them empty) isolated by clipping; this converter flattens everything at page level with no clipping, so curves overflow into neighbouring graphics. The reference also keeps only 22 skeleton lines document-wide (widths clustered at 0.75 / 2 / 3), discarding the PDF's 190 strokes. Both points have been confirmed as out of scope.
Resource and security notes
This converter parses external PDF files.
- Memory: per-page operator lists, decoded images and gradient prefetch tables all live in memory. High-resolution scans of hundreds of pages can use substantial memory (a 14-page paper sample peaked around 200 MB).
- 8-second image wait ceiling:
waitImages()polls pdf.js for asynchronously delivered image data and treats anything past 8 seconds as ready (missing images are skipped without an error). In extreme cases images can be silently absent. - PDF signatures are not verified. If the input PDF carries a digital signature, this tool does not validate it — it only converts content.
- Parser hardening is pdf.js's job. This converter adds no extra sandboxing. Run it in a constrained environment (container / low-privilege process) for PDFs from untrusted sources.
Known limitations
- Not supported: form fields, annotations, Type3 fonts
- Radial gradients are approximated as axial; strict visual parity is unverified
- Tiling patterns keep only their average colour — the halftone texture itself is not reproduced;
...ColorNspaces other than pattern images (Indexed / CMYK / Lab) fall back to the previous colour - Image-heavy PDFs grow: pdf.js hands over decoded pixels, so re-encoded PNGs are usually larger than the source JPEGs — scans especially so
- Text spacing is approximated: per-glyph
DeltaXsplits the total width evenly; long Latin runs may drift slightly (CJK is accurate since it is monospaced) - CropBox offsets are not specially handled; page size comes from
page.view - Beta: this module is in beta; its API and behavior may change as it evolves. Not all PDF features are covered — manually verify the output before formal archiving, contracts, invoices or similar use
Maintainer notes
The following are not synced automatically — handle them manually before publishing:
| Item | Location | Notes |
| --- | --- | --- |
| npm package version | PKG.version in build/build-pdf2ofd-npm.js | Read automatically from the repository-root package.json version, kept in sync with the dist/<version>/ folder |
| npm package name | PKG.name in build/build-pdf2ofd-npm.js | Change it if pdf2ofd is taken on npmjs |
| Release-package file stripping | distTransform() in build/common.js | After changing the structure of web/viewer.html / web/viewer.js (selectors, events, the test-file default), the regexes stop matching. Assertions now make the build fail loudly instead of silently shipping a broken package |
npm run build:pdf2ofd-npm only reassembles dist/<version>/pdf2ofd/; it does not publish. Publishing is a separate step:
cd dist/<version>/pdf2ofd
npm publish --access publicTroubleshooting
After changing the converter, run the baseline sample and check the reported counts (should be 14 pages / 24 fonts / 90 images):
node build/pdf2ofd/pdf2ofd.js test/<your-sample>.pdf /tmp/chk.ofdFor deeper product verification (ZIP entries inflate and match their CRC32, PNG chunk CRCs, MultiMedia declarations == image entries == per-page ImageObject total) write a throwaway script — but mind three traps:
- ZIP headers are little-endian; PNG chunk headers are big-endian. Mixing them yields a bogus "0 entries" reading.
- Structural validation passing ≠ content being correct. Signature, dimensions, CRC and inflate can all pass while the pixels are entirely wrong. Any image-encoding change needs a byte-for-byte pixel comparison.
- "No all-zero CTMs" is not a sufficient check. When page 11 lost its colours, all-zero CTM paths were 0 and stroked paths were 8 — both healthy — yet 81 gradient bars had been silently dropped. You have to count by graphic type (AxialShd count, ImageObject count, TextObject count) to localise such failures.
When diagnosing display problems, reuse the project's existing ofd/core/zip.js instead of hand-rolling another ZIP reader.
Six general rules
These were re-verified repeatedly while building this converter. Check every one of them before changing the code:
LineWidth/DashPatternshare the coordinate space ofAbbreviatedData— never pre-multiply by the CTMDashPatternis a PathObject attribute, not a child element- pdf.js consumes clip one step late;
clipitself carries no path fmt()'s 4 decimal places are fatal for tiny CTMs — absorb the scale into the coordinates instead- Any
page.objs.get()id lookup must be preceded by anawaitprefetch - One
endPathcan be both a clip region and a fill region — you cannot have just one
