如何将多张图片转换为单个PDF文件,相关应用功能如何实现?
图片转单PDF功能实现方案
无论使用哪种技术栈实现,核心逻辑都是固定的:
- 遍历指定文件夹,筛选出符合格式的图片文件(支持jpg、png、bmp、tiff等常用格式)
- 按业务需求对图片做预处理:比如统一尺寸、调整分辨率、压缩体积、按文件名/创建时间排序
- 逐页将图片写入PDF文档,可设置每页尺寸匹配图片大小或使用统一规范尺寸
- 输出最终合并后的PDF文件到指定路径
Python实现(适合脚本/后端服务场景)
推荐用轻量的Pillow库实现:
首先安装依赖:pip install pillow
代码示例:
from PIL import Image import os def images_to_pdf(folder_path, output_pdf_path, sort_by='name'): # 筛选支持的图片格式 img_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff') img_list = [] # 遍历文件夹获取所有图片 for filename in os.listdir(folder_path): if filename.lower().endswith(img_extensions): img_path = os.path.join(folder_path, filename) img = Image.open(img_path).convert('RGB') img_list.append((filename, img)) # 按指定规则排序,默认按文件名升序 if sort_by == 'name': img_list.sort(key=lambda x: x[0]) elif sort_by == 'ctime': img_list.sort(key=lambda x: os.path.getctime(os.path.join(folder_path, x[0]))) # 提取排序后的图片对象 sorted_imgs = [item[1] for item in img_list] if sorted_imgs: # 第一张图片作为第一页,后续图片依次追加 sorted_imgs[0].save(output_pdf_path, save_all=True, append_images=sorted_imgs[1:]) return True return False # 调用示例 images_to_pdf('./你的图片文件夹路径', './输出PDF路径.pdf')
如果需要实现加边距、页眉页脚等复杂排版,可以配合PyPDF2、reportlab库使用。
Java实现(适合后端服务场景)
推荐用Apache PDFBox库实现,Maven依赖如下:
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.32</version> </dependency>
核心代码逻辑:
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; public class ImageToPdf { public static void convert(String folderPath, String outputPath) throws IOException { // 筛选图片文件 List<Path> imgPaths = Files.list(Path.of(folderPath)) .filter(p -> p.getFileName().toString().toLowerCase().matches(".*\\.(png|jpg|jpeg|bmp)$")) .sorted() .collect(Collectors.toList()); try (PDDocument document = new PDDocument()) { for (Path imgPath : imgPaths) { PDPage page = new PDPage(); document.addPage(page); try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { PDImageXObject image = PDImageXObject.createFromFile(imgPath.toString(), document); // 适配页面大小,可自定义缩放比例 float scale = Math.min(page.getMediaBox().getWidth() / image.getWidth(), page.getMediaBox().getHeight() / image.getHeight()); float x = (page.getMediaBox().getWidth() - image.getWidth() * scale) / 2; float y = (page.getMediaBox().getHeight() - image.getHeight() * scale) / 2; contentStream.drawImage(image, x, y, image.getWidth() * scale, image.getHeight() * scale); } } document.save(outputPath); } } }
Node.js实现(适合全栈/浏览器端场景)
服务端Node环境可以用pdf-lib库实现:
首先安装依赖:npm install pdf-lib fs-extra
核心代码示例:
const { PDFDocument } = require('pdf-lib'); const fs = require('fs-extra'); const path = require('path'); async function imagesToPdf(folderPath, outputPath) { const pdfDoc = await PDFDocument.create(); const imgExts = ['.png', '.jpg', '.jpeg']; const files = await fs.readdir(folderPath); const imgFiles = files .filter(f => imgExts.includes(path.extname(f).toLowerCase())) .sort(); for (const file of imgFiles) { const imgBuffer = await fs.readFile(path.join(folderPath, file)); let img; if (file.endsWith('.png')) { img = await pdfDoc.embedPng(imgBuffer); } else { img = await pdfDoc.embedJpg(imgBuffer); } const page = pdfDoc.addPage([img.width, img.height]); page.drawImage(img, { x: 0, y: 0, width: img.width, height: img.height }); } const pdfBytes = await pdfDoc.save(); await fs.writeFile(outputPath, pdfBytes); }
如果是浏览器端场景,可以直接在前端获取用户上传的图片文件后,用pdf-lib在内存中生成PDF供用户下载,不需要上传到服务端。
内容的提问来源于stack exchange,提问作者Mohsin Editx
相关产品推荐
相关产品推荐

