python将图片转换为pdf
时间: 2024-05-12 11:19:28 浏览: 105
您可以使用Python的PyPDF2库将图像转换为PDF。以下是一个示例代码:
```python
import os
from PIL import Image
from io import BytesIO
from PyPDF2 import PdfFileWriter, PdfFileReader
def convert_images_to_pdf(images, output_file):
pdf_writer = PdfFileWriter()
for image in images:
image_file = BytesIO()
image.save(image_file, 'JPEG')
pdf_writer.addPage(
PdfFileReader(BytesIO(image_file.getvalue())).getPage(0))
with open(output_file, 'wb') as out:
pdf_writer.write(out)
if __name__ == '__main__':
image_folder = '/path/to/folder/containing/images'
output_file = '/path/to/output/pdf/file.pdf'
images = []
for filename in os.listdir(image_folder):
if filename.endswith('.jpg') or filename.endswith('.jpeg'):
image = Image.open(os.path.join(image_folder, filename))
images.append(image)
convert_images_to_pdf(images, output_file)
```
这将读取指定文件夹中的所有JPEG图像,并将它们添加到PDF文件中。请注意,您需要安装Pillow库(即PIL库的分支)来处理图像,并且需要安装PyPDF2库来处理PDF。
阅读全文