有时候,你可能需要把一些图像文件整理成一个 PDF 文件,以便于打印,分享或存档。例如,你可能想把一些扫描的文档,照片或漫画转换为 PDF 文件。或者,你可能想把一些数据可视化的图表或报告转换为 PDF 文件。使用 img2pdf 库,你可以快速地完成这些任务,而不需要安装其他的软件或工具。
pip install img2pdf
等待安装完成后,你就可以开始使用 img2pdf 库了。
import img2pdf images = ["cat.jpg", "dog.jpg", "bird.jpg"] output = "animals.pdf" # 创建一个PDF文件 并以二进制方式写入 with open(output, "wb") as f: # convert函数 用来转PDF write_content = img2pdf.convert(images) f.write(write_content) # 写入文件 print("转换成功!") # 提示语运行这段代码后,你就会在当前目录下看到一个名为 animals.pdf 的文件。打开它,你就会看到三张图像按照顺序排列在不同的页面上。
import img2pdf from PIL import Image # List of image file paths image_paths = ["cat.jpg", "dog.jpg", "bird.jpg"] output = "animals.pdf" # Function to resize and rotate images def resize_and_rotate_image(image_path): # Open the image using PIL image = Image.open(image_path) # Rotate the image to landscape orientation image = image.rotate(90, expand=True) # Return the modified image image.save("new—"+image_path) return "new—"+image_path # List to store modified images modified_images = [] # Loop through each image path for path in image_paths: # Resize and rotate the image modified_image = resize_and_rotate_image(path) modified_images.append(modified_image) # Convert modified images to PDF pdf_bytes = img2pdf.convert(modified_images) # Save the PDF to a file with open(output, "wb") as f: f.write(pdf_bytes)运行这段代码后,你就会得到一个不同的 PDF 文件,其中所有的图像都都横向显示。