Node.js PDF签名库,用于调用Java JAR文件进行PDF数字签名
npm install @moneyinto/node-sign-pdfNode.js PDF签名库,用于调用Java JAR文件进行PDF数字签名。
- 支持PDF文件数字签名
- 支持自定义签名原因和位置
- 简单易用的API
- 基于Java实现,确保签名兼容性
1. 克隆或下载项目到本地
2. 安装依赖(如果需要)
``bash`
npm install
3. 或通过npm安装(如果已发布到npm)
`bash`
npm install node-sign-pdf
`javascript
// CommonJS 示例
const { signPdf } = require('node-sign-pdf');
const path = require('path');
async function main() {
try {
const inputPath = path.join(__dirname, 'test-unsigned.pdf');
const outputPath = path.join(__dirname, 'test-signed.pdf');
const keystorePath = path.join(__dirname, 'keystore.p12');
console.log('开始签名PDF...');
const result = await signPdf(inputPath, outputPath, keystorePath, 'your-password', 'your-user-password', 'your-owner-password');
console.log('PDF签名成功:', result);
} catch (error) {
console.error('PDF签名失败:', error);
}
}
main();
// ES Module 示例
import signPdf from 'node-sign-pdf';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
async function main() {
try {
const inputPath = path.join(__dirname, 'test-unsigned.pdf');
const outputPath = path.join(__dirname, 'test-signed.pdf');
const keystorePath = path.join(__dirname, 'keystore.p12');
console.log('开始签名PDF...');
const result = await signPdf(inputPath, outputPath, keystorePath, 'your-password', 'your-user-password', 'your-owner-password');
console.log('PDF签名成功:', result);
} catch (error) {
console.error('PDF签名失败:', error);
}
}
main();
`
项目包含一个测试脚本,可用于验证签名功能:
`bash`
npm test
对PDF文件进行数字签名。
#### 参数
- inputPath (string): 输入PDF文件路径outputPath
- (string): 输出PDF文件路径keystorePath
- (string): 密钥库文件路径keystorePassword
- (string): 密钥库密码pdfUserPassword
- (string): PDF用户密码pdfOwnerPassword
- (string): PDF所有者密码
#### 返回值
- Promise: 返回输出文件路径
``
node-sign-pdf/
├── index.js # 主入口文件
├── package.json # 项目配置文件
├── fat-pdf-signer.jar # PDF签名Java JAR文件
├── example/ # 测试用未签名PDF文件和测试脚本
└── README.md # 项目文档
- 核心依赖:
- child_process (Node.js内置模块): 用于执行Java命令path
- (Node.js内置模块): 用于处理文件路径
- 开发依赖:
- pdfkit (可选): 用于生成测试PDF文件
如果需要测试签名功能,可以使用以下命令生成自签名证书:
1. 生成私钥:
`bash`
openssl genrsa -out private.key 2048
2. 生成证书签名请求:
`bash`
openssl req -new -key private.key -out certificate.csr
3. 生成自签名证书:
`bash`
openssl x509 -req -days 365 -in certificate.csr -signkey private.key -out certificate.crt
4. 导出为PKCS#12格式:
`bash`
openssl pkcs12 -export -out keystore.p12 -inkey private.key -in certificate.crt
`bash`
keytool -genkeypair -alias myalias -keyalg RSA -keysize 2048 -keystore keystore.p12 -storetype PKCS12 -validity 365 -storepass your-password
1. 确保Java环境已正确安装并配置在系统PATH中
2. 密钥库文件应妥善保管,避免泄露
3. 自签名证书仅适用于测试环境,生产环境应使用受信任CA颁发的证书
4. 签名操作会修改PDF文件,建议在签名前备份原始文件
1. Java命令未找到
- 确保Java已安装并添加到系统PATH
- 检查java -version命令是否能正常执行
2. 密钥库文件不存在
- 确保提供了正确的密钥库文件路径
- 检查密钥库文件是否存在且可读
3. 密码错误
- 确保提供了正确的密钥库密码
4. 别名不存在
- 确保提供了正确的密钥别名
- 使用keytool -list -v -keystore keystore.p12 -storetype PKCS12 -storepass your-password`查看可用别名