要将图片转换为PDF,您可以使用Python的第三方库 `reportlab` 或 `img2pdf`。以下是使用这些库的示例代码:
使用 `reportlab`
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from PIL import Image
def convert_images_to_pdf(image_paths, output_path):
c = canvas.Canvas(output_path, pagesize=letter)
for image_path in image_paths:
img = Image.open(image_path)
c.drawImage(image_path, 0, 0, width=img.size, height=img.size)
c.showPage()
c.save()
示例用法
image_paths = ['image1.jpg', 'image2.jpg']
output_path = 'output.pdf'
convert_images_to_pdf(image_paths, output_path)
使用 `img2pdf`
from img2pdf import convert
from PIL import Image
def convert_images_to_pdf(image_paths, output_path):
images = [Image.open(img_path).convert('RGB') for img_path in image_paths]
with open(output_path, 'wb') as output_file:
convert(images, output_file)
示例用法
image_paths = ['image1.jpg', 'image2.jpg']
output_path = 'output.pdf'
convert_images_to_pdf(image_paths, output_path)
请确保在运行代码之前已经安装了相应的库。您可以使用 `pip` 来安装这些库:
pip install reportlab
pip install img2pdf
pip install Pillow