要将Python中的图片转换为PDF文件,您可以使用Pillow库或ReportLab库。以下是使用Pillow库将图片转换为PDF文件的示例代码:
```python
from PIL import Image
def image_to_pdf(image_path, output_path):
image = Image.open(image_path)
image.convert('RGB').save(output_path, 'PDF')
print(f"已将图片 {image_path} 转换为 PDF 文件 {output_path}")
示例使用
image_to_pdf('example.jpg', 'output.pdf')
如果您需要将多张图片合并为一个PDF文件,可以使用以下代码:
```python
from PIL import Image
def images_to_pdf(image_paths, output_path):
images = [Image.open(image).convert('RGB') for image in image_paths]
images.save(output_path, save_all=True, append_images=images[1:])
示例使用
image_paths = ['example1.jpg', 'example2.jpg']
images_to_pdf(image_paths, 'output.pdf')
如果您需要更高级的功能,比如调整图像大小或添加文本,可以使用ReportLab库。以下是使用ReportLab库将图片转换为PDF文件的示例代码:
```python
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from PIL import Image
def jpg_to_pdf(jpg_path, pdf_path):
c = canvas.Canvas(pdf_path, pagesize=letter)
img = Image.open(jpg_path)
c.drawImage(jpg_path, 0, 0, width=img.size, height=img.size)
c.showPage()
c.save()
示例使用
jpg_to_pdf('code.png', 'code.pdf')
请确保在运行代码之前已经安装了相应的库。您可以使用pip命令来安装Pillow和ReportLab库:
```
pip install Pillow reportlab