python 图片转pdf合并
时间: 2025-06-21 07:28:20 浏览: 13
### 使用Python将多个图像文件转换为单个PDF文件
为了完成此任务,可以采用多种方法和库来处理图像到PDF的转换。以下是几种常用的技术。
#### 方法一:使用Pillow库
Pillow是Python Imaging Library (PIL)的一个分支,提供了广泛的图像处理功能。通过该库能够轻松地加载、修改以及保存各种格式的图像数据至PDF文档中[^1]。
```python
from PIL import Image
images = []
for filename in ["image1.jpg", "image2.png"]:
im = Image.open(filename)
images.append(im)
# Save the first image along with all others as a PDF document.
images[0].save(
"output.pdf",
save_all=True,
append_images=images[1:]
)
```
这种方法简单易懂,并且对于大多数情况下都适用良好。
#### 方法二:利用Fitz(PyMuPDF)
当涉及到更复杂的操作时,比如调整页面大小或添加额外元数据,则可以选择更为强大的工具——Mupdf引擎背后的封装器之一即`fitz`(也称为`pymupdf`)。这个库允许创建高质量的PDF输出的同时还支持其他高级特性[^3]。
```python
import fitz # PyMuPDF
doc = fitz.open()
for img_path in ["img1.jpg", "img2.png"]: # list of your images here
img_doc = fitz.open(img_path) # open image file
pdf_bytes = img_doc.convert_to_pdf() # convert to PDF bytes
img_pdf = fitz.open("pdf", pdf_bytes) # create temporary PDF from those bytes
doc.insert_pdf(img_pdf) # insert into final output PDF
doc.save("combined_output.pdf") # save combined PDF
```
这段代码展示了如何遍历一系列图片路径并将它们逐个加入到一个新的PDF文件里去。
#### 方法三:借助reportlab生成自定义布局
如果希望对最终生成的内容有更多的控制权,那么ReportLab可能是个不错的选择。它可以用来构建具有特定样式和结构化的PDF报告,在其中嵌入图形资源也很方便。
```python
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Image
def add_image(doc, path):
img = Image(path)
width, height = letter
aspect_ratio = float(img.drawHeight / img.drawWidth)
new_width = min(width, 792 * aspect_ratio) # limit max size while preserving AR
new_height = int(new_width * aspect_ratio)
img._restrictSize((new_width, new_height))
doc.build([img])
document = SimpleDocTemplate('custom_layout.pdf', pagesize=letter)
for pic_file in ['pic1.bmp', 'pic2.gif']:
add_image(document, pic_file)
```
这里展示了一个函数用于向指定模板对象内追加经过适当缩放后的静态图件实例;随后循环调用以填充整个文档主体部分。
以上三种方式都可以有效地把多张不同类型的位图组合成单一形式存储介质上的电子档材料。具体选择取决于实际需求和个人偏好等因素考虑下的最佳实践方案。
阅读全文
相关推荐
















