要将图片转换为PDF,您可以使用Python的第三方库 `reportlab` 或 `img2pdf`。以下是使用这些库的示例代码:
使用 `reportlab`
python
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`
python
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` 来安装这些库:
bash
pip install reportlab
pip install img2pdf
pip install Pillow
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/49231.html