node-pdf2img
v0.1.14
Published
High-performance PDF to image converter using PDFium native renderer or PDF.js
Maintainers
Readme
node-pdf2img
高性能 PDF 转图片工具,支持 PDFium 原生渲染器和 PDF.js 渲染器。
特性
- 双渲染引擎:PDFium 原生渲染(高性能)+ PDF.js(纯 JavaScript,无需原生依赖)
- 高性能:PDFium 多线程并行处理,整体快 1.7x
- 流式渲染:URL 输入支持 HTTP Range 请求,大文件无需完整下载
- 多种格式:支持 WebP、PNG、JPG 输出
- 多种输入:支持本地文件、URL、Buffer
- 多种输出:支持本地文件、Buffer、腾讯云 COS
- CLI + API:命令行工具和 Node.js 模块双模式
- 广泛兼容:支持 GLIBC 2.17+ (CentOS 7/RHEL 7+)
安装
# 作为项目依赖安装(API 使用)
npm install node-pdf2img
# 全局安装(CLI 使用)
npm install -g node-pdf2img系统要求
- Node.js >= 18.0.0
- 支持平台:
- Linux x64/arm64 (GLIBC 2.17+,兼容 CentOS 7/RHEL 7+)
- macOS x64/arm64
- Windows x64
CLI 使用
# 基本用法 - 转换所有页面(默认使用 PDFium)
pdf2img document.pdf -o ./output
# 使用 PDF.js 渲染器
pdf2img document.pdf -o ./output -r pdfjs
# 转换指定页面
pdf2img document.pdf -p 1,2,3 -o ./output
# 从 URL 转换
pdf2img https://example.com/document.pdf -o ./output
# 自定义质量和宽度
pdf2img document.pdf -q 90 -w 2560 -o ./output
# 输出 PNG 格式
pdf2img document.pdf -f png -o ./output
# 输出 JPG 格式
pdf2img document.pdf -f jpg -q 85 -o ./output
# 显示 PDF 信息
pdf2img document.pdf --info
# 显示渲染器版本信息
pdf2img --version-info
# 上传到腾讯云 COS
pdf2img document.pdf --cos --cos-prefix images/doc-123CLI 选项
| 选项 | 说明 | 默认值 |
|------|------|--------|
| -o, --output <dir> | 输出目录 | ./output |
| -p, --pages <pages> | 页码(逗号分隔) | 全部页面 |
| -w, --width <width> | 渲染宽度(像素) | 1920 |
| -q, --quality <quality> | 图片质量(0-100) | 100 |
| -f, --format <format> | 输出格式:webp, png, jpg | webp |
| -r, --renderer <renderer> | 渲染器:pdfium, pdfjs | pdfium |
| --prefix <prefix> | 文件名前缀 | page |
| --info | 仅显示 PDF 信息 | |
| --version-info | 显示渲染器版本信息 | |
| -v, --verbose | 详细输出 | |
| --cos | 上传到腾讯云 COS | |
| --cos-prefix <prefix> | COS key 前缀 | |
COS 上传配置
# 设置环境变量
export COS_SECRET_ID=your-secret-id
export COS_SECRET_KEY=your-secret-key
export COS_BUCKET=your-bucket-name
export COS_REGION=ap-guangzhou
# 使用 --cos 选项上传
pdf2img document.pdf --cos --cos-prefix images/doc-123API 使用
基本用法
import { convert, getPageCount, isAvailable, RendererType } from 'node-pdf2img';
// 检查渲染器是否可用
if (!isAvailable()) {
console.error('原生渲染器不可用');
process.exit(1);
}
// 转换 PDF 为图片(返回 Buffer,默认使用 PDFium)
const result = await convert('./document.pdf');
console.log(`转换了 ${result.renderedPages} 页`);
for (const page of result.pages) {
console.log(`第 ${page.pageNum} 页: ${page.width}x${page.height}`);
// page.buffer 包含图片数据
}使用 PDF.js 渲染器
import { convert, RendererType, isPdfjsAvailable } from 'node-pdf2img';
// 检查 PDF.js 渲染器是否可用
if (isPdfjsAvailable()) {
const result = await convert('./document.pdf', {
renderer: RendererType.PDFJS, // 或直接使用 'pdfjs'
});
console.log(`使用 PDF.js 转换了 ${result.renderedPages} 页`);
}渲染器选择建议:
- PDFium(默认):高性能,适合大多数场景,整体快 1.7x
- PDF.js:纯 JavaScript,无需原生依赖,适合超大文件(>50MB)或无法使用原生模块的环境
保存到文件
const result = await convert('./document.pdf', {
outputType: 'file',
outputDir: './output',
prefix: 'doc',
});
for (const page of result.pages) {
console.log(`已保存: ${page.outputPath}`);
}指定输出格式
// PNG 格式
await convert('./document.pdf', {
format: 'png',
outputType: 'file',
outputDir: './output',
});
// JPG 格式,指定质量
await convert('./document.pdf', {
format: 'jpg',
jpeg: { quality: 85 },
outputType: 'file',
outputDir: './output',
});
// WebP 格式,指定质量
await convert('./document.pdf', {
format: 'webp',
webp: { quality: 80 },
outputType: 'file',
outputDir: './output',
});转换指定页面
const result = await convert('./document.pdf', {
pages: [1, 2, 3],
outputType: 'file',
outputDir: './output',
});pages 参数说明
pages 参数控制要转换的页面:
- 空数组
[]或不传:转换所有页面 - 指定页码数组:只转换指定页面(1-based)
// 转换所有页面(推荐)
await convert('./document.pdf', { pages: [] });
// 只转换第 1、3、5 页
await convert('./document.pdf', { pages: [1, 3, 5] });最佳实践:如果需要转换所有页面,直接使用
convert()并传空pages数组,不要先调用getPageCount()获取页数再传入。这样可以避免 URL 输入时重复下载 PDF 文件。// ❌ 不推荐:URL 会被下载两次 const pageCount = await getPageCount(url); const result = await convert(url, { pages: Array.from({length: pageCount}, (_, i) => i + 1) }); // ✅ 推荐:直接转换所有页面 const result = await convert(url, { pages: [] });
自定义渲染宽度
const result = await convert('./document.pdf', {
targetWidth: 2560,
outputType: 'file',
outputDir: './output',
});从 URL 转换
const result = await convert('https://example.com/document.pdf', {
outputType: 'file',
outputDir: './output',
});
// 查看流式渲染统计(仅 URL 输入时存在)
if (result.streamStats) {
console.log(`流式渲染: 缓存命中 ${result.streamStats.cacheHits} 次`);
}流式渲染:对于大于 2MB 的远程 PDF,会自动使用 HTTP Range 请求按需获取数据,避免完整下载。小于 2MB 的文件会直接下载后渲染,减少 Range 请求开销。
上传到腾讯云 COS
const result = await convert('./document.pdf', {
outputType: 'cos',
cos: {
secretId: 'your-secret-id',
secretKey: 'your-secret-key',
bucket: 'your-bucket',
region: 'ap-guangzhou',
},
cosKeyPrefix: 'pdf-images/doc-123',
});
for (const page of result.pages) {
console.log(`已上传: ${page.cosKey}`);
}获取页数
const pageCount = await getPageCount('./document.pdf');
console.log(`PDF 共 ${pageCount} 页`);线程池管理
import { getThreadPoolStats, destroyThreadPool } from 'node-pdf2img';
// 获取线程池统计
const stats = getThreadPoolStats();
console.log(`工作线程: ${stats.workers}`);
// 应用关闭时销毁线程池
await destroyThreadPool();API 参考
convert(input, options?)
PDF 转图片。
参数:
input(string | Buffer):PDF 文件路径、URL 或 Bufferoptions(object):转换选项pages(number[]):要转换的页码(1-based),空数组表示全部outputType('file' | 'buffer' | 'cos'):输出类型,默认 'buffer'outputDir(string):输出目录('file' 类型时必需)prefix(string):文件名前缀,默认 'page'format('webp' | 'png' | 'jpg'):输出格式,默认 'webp'targetWidth(number):渲染宽度,默认 1280renderer('pdfium' | 'pdfjs'):渲染器,默认 'pdfium'webp(object):WebP 编码选项quality(number):质量 0-100,默认 80
jpeg(object):JPEG 编码选项quality(number):质量 0-100,默认 85
png(object):PNG 编码选项compressionLevel(number):压缩级别 0-9,默认 6
cos(object):COS 配置('cos' 类型时必需)cosKeyPrefix(string):COS key 前缀
返回: Promise<ConvertResult>
getPageCount(input)
获取 PDF 页数。
参数:
input(string | Buffer):PDF 文件路径或 Buffer
返回: Promise<number>
isAvailable(renderer?)
检查渲染器是否可用。
参数:
renderer('pdfium' | 'pdfjs'):可选,指定检查的渲染器,默认检查 PDFium
返回: boolean
isPdfjsAvailable()
检查 PDF.js 渲染器是否可用。
返回: boolean
getVersion()
获取 PDFium 渲染器版本信息。
返回: string
getPdfjsVersion()
获取 PDF.js 渲染器版本信息。
返回: string
destroyThreadPool()
销毁线程池,释放资源。
返回: Promise<void>
环境变量
| 变量 | 说明 | 默认值 |
|------|------|--------|
| PDF2IMG_THREAD_COUNT | 工作线程数 | CPU 核心数 |
| PDF2IMG_RENDERER | 默认渲染器 (pdfium/pdfjs) | pdfium |
| PDF2IMG_DEBUG | 启用调试日志 | false |
渲染器对比
| 特性 | PDFium | PDF.js | |------|--------|--------| | 性能 | ⚡ 快 1.7x | 普通 | | 依赖 | 原生模块 | 纯 JavaScript | | 大文件 (>50MB) | 普通 | ⚡ 更快 | | 兼容性 | Linux/macOS/Windows | 所有平台 | | 流式渲染 | ✓ | ✓ |
架构
模块化设计,职责分离:
src/
├── core/
│ ├── converter.js # 主 API 入口
│ ├── renderer.js # PDF 渲染逻辑(流式/下载/本地)
│ ├── thread-pool.js # 线程池管理
│ ├── downloader.js # 远程文件下载
│ ├── output-handler.js # 文件保存和 COS 上传
│ └── config.js # 配置常量
├── renderers/
│ ├── native.js # PDFium 原生渲染器
│ └── pdfjs.js # PDF.js 渲染器(分片加载)
└── utils/
└── logger.js # 日志工具许可证
MIT
