多图片生成pdf

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
const { PDFDocument } = require('pdf-lib');
const fs = require('fs-extra');
const path = require('path');
const { glob } = require('glob');

/**
* 将指定目录下的图片转换为PDF文件
* @param {string} imageDir 图片目录路径
* @param {string} outputPdfPath 输出PDF文件路径
* @param {Object} options 配置选项
*/
async function convertImagesToPdf(imageDir, outputPdfPath, options = {}) {
const {
imageExtensions = ['jpg', 'jpeg', 'png'],
maxRetries = 3,
showProgress = true,
pageSize = 'auto'
} = options;

try {
// 检查图片目录是否存在
if (!await fs.pathExists(imageDir)) {
throw new Error(`图片目录不存在: ${imageDir}`);
}

if (showProgress) {
console.log(`正在搜索目录: ${imageDir}`);
console.log(`支持的图片格式: ${imageExtensions.join(', ')}`);
}

// 构建图片文件的glob模式
const patterns = imageExtensions.map(ext =>
path.join(imageDir, `*.${ext}`)
);

// 查找所有匹配的图片文件
let imageFiles = [];
for (const pattern of patterns) {
try {
const files = await glob(pattern, { windowsPathsNoEscape: true });
if (showProgress) {
console.log(`模式 ${pattern} 找到 ${files.length} 个文件`);
}
imageFiles = [...imageFiles, ...files];
} catch (error) {
console.error(`搜索模式 ${pattern} 时出错:`, error.message);
}
}

if (imageFiles.length === 0) {
console.log(`在目录 ${imageDir} 中没有找到任何图片文件`);
return;
}

// 按文件名排序
imageFiles.sort((a, b) => {
const fileNameA = path.basename(a).toLowerCase();
const fileNameB = path.basename(b).toLowerCase();
return fileNameA.localeCompare(fileNameB, undefined, { numeric: true, sensitivity: 'base' });
});

if (showProgress) {
console.log(`找到 ${imageFiles.length} 个图片文件,准备转换为PDF...`);
}

// 创建一个新的PDF文档
const pdfDoc = await PDFDocument.create();

// 为每个图片添加一页PDF
let successCount = 0;
let errorCount = 0;

for (let i = 0; i < imageFiles.length; i++) {
const imagePath = imageFiles[i];
let retryCount = 0;
let success = false;

while (retryCount < maxRetries && !success) {
try {
if (showProgress) {
console.log(`正在处理: ${path.basename(imagePath)} (${i + 1}/${imageFiles.length})`);
}

// 读取图片文件
const imageBytes = await fs.readFile(imagePath);

// 根据文件扩展名判断图片类型并添加到PDF
let pdfImage;
const ext = path.extname(imagePath).toLowerCase();

if (ext === '.jpg' || ext === '.jpeg') {
pdfImage = await pdfDoc.embedJpg(imageBytes);
} else if (ext === '.png') {
pdfImage = await pdfDoc.embedPng(imageBytes);
} else {
console.log(`跳过不支持的文件类型: ${imagePath}`);
break;
}

// 获取图片尺寸
const imageDims = pdfImage.scale(1);

// 添加一页,尺寸与图片相同
const page = pdfDoc.addPage([imageDims.width, imageDims.height]);

// 将图片绘制到页面上
page.drawImage(pdfImage, {
x: 0,
y: 0,
width: imageDims.width,
height: imageDims.height,
});

if (showProgress) {
console.log(`成功添加页面: ${path.basename(imagePath)} (${imageDims.width}x${imageDims.height})`);
}

success = true;
successCount++;

} catch (error) {
retryCount++;
if (retryCount < maxRetries) {
console.warn(`处理图片 ${path.basename(imagePath)} 时出错,正在重试 (${retryCount}/${maxRetries}):`, error.message);
await new Promise(resolve => setTimeout(resolve, 1000));
} else {
console.error(`处理图片 ${path.basename(imagePath)} 失败,已重试 ${maxRetries} 次:`, error.message);
errorCount++;
}
}
}
}

if (showProgress) {
console.log(`\n处理完成: 成功 ${successCount} 个,失败 ${errorCount} 个`);
}

// 保存PDF到文件
if (showProgress) {
console.log('正在保存PDF文件...');
}

const pdfBytes = await pdfDoc.save();
await fs.writeFile(outputPdfPath, pdfBytes);

console.log(`\n✅ PDF文件已成功创建: ${outputPdfPath}`);
console.log(`📊 PDF大小: ${(pdfBytes.length / 1024 / 1024).toFixed(2)} MB`);
console.log(`📄 总页数: ${successCount}`);

} catch (error) {
console.error('❌ 转换过程中发生错误:', error.message);
throw error;
}
}

// 命令行参数处理
function parseArguments() {
const args = process.argv.slice(2);
const options = {
imageDir: './images',
outputPdf: './output.pdf',
imageExtensions: ['jpg', 'jpeg', 'png'],
maxRetries: 3
};

for (let i = 0; i < args.length; i++) {
const arg = args[i];
switch (arg) {
case '--help':
case '-h':
console.log(`
图片转PDF工具

用法: node imgtopdf.js [选项]

选项:
--input, -i <目录> 输入图片目录 (默认: ./images)
--output, -o <文件> 输出PDF文件 (默认: ./output.pdf)
--extensions, -e <扩展名> 图片扩展名,用逗号分隔 (默认: jpg,jpeg,png)
--retries, -r <次数> 最大重试次数 (默认: 3)
--help, -h 显示此帮助信息

示例:
node imgtopdf.js --input ./photos --output photos.pdf
node imgtopdf.js -i ./images -o output.pdf
`);
process.exit(0);
break;
case '--input':
case '-i':
options.imageDir = args[++i];
break;
case '--output':
case '-o':
options.outputPdf = args[++i];
break;
case '--extensions':
case '-e':
options.imageExtensions = args[++i].split(',').map(ext => ext.trim());
break;
case '--retries':
case '-r':
options.maxRetries = parseInt(args[++i]);
break;
}
}

return options;
}

// 主函数
async function main() {
try {
const options = parseArguments();

console.log('🚀 开始图片转PDF转换...');
console.log(`📁 输入目录: ${options.imageDir}`);
console.log(`📄 输出文件: ${options.outputPdf}`);
console.log(`🖼️ 图片格式: ${options.imageExtensions.join(', ')}`);
console.log(`🔄 最大重试: ${options.maxRetries}次\n`);

await convertImagesToPdf(options.imageDir, options.outputPdf, options);

console.log('\n🎉 转换完成!');
} catch (error) {
console.error('\n💥 程序执行失败:', error.message);
process.exit(1);
}
}

// 如果直接运行此文件,则执行主函数
if (require.main === module) {
main();
}

// 导出函数供其他模块使用
module.exports = { convertImagesToPdf };