批量将 WebP 图片转换为 PDF 文件
前言
在一次爬取网站时,获取到了大量的 .webp
格式图片,想将这些图片批量转换为 PDF 文件。不过在我尝试使用 Adobe Acrobat Pro 进行转换的时候,显示警告无法完成转换。随后使用了Python解决这个问题,希望对有类似需求的朋友有所帮助。
代码实现
确保安装了Pillow库:
pip install Pillow
以下是完整的代码:
from PIL import Image
import os
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def webp_to_pdf(folder_path, output_pdf):
# 获取所有.webp文件
webp_files = [f for f in os.listdir(folder_path) if f.lower().endswith('.webp')]
webp_files.sort() # 按文件名排序
if not webp_files:
print("文件夹中没有找到.webp文件")
return
# 打开第一张图片
first_image = Image.open(os.path.join(folder_path, webp_files[0])).convert('RGB')
# 转换其余的图片
other_images = []
for webp_file in webp_files[1:]:
try:
image_path = os.path.join(folder_path, webp_file)
image = Image.open(image_path).convert('RGB')
other_images.append(image)
except Exception as e:
print(f"处理{webp_file}时出错: {e}")
# 保存为PDF
first_image.save(output_pdf, "PDF", save_all=True, append_images=other_images)
print(f"PDF已保存为: {output_pdf}")
# 使用示例
if __name__ == "__main__":
folder_path = r"Path" # 替换为图片文件夹路径
output_pdf = "output.pdf" # PDF输出路径
try:
webp_to_pdf(folder_path, output_pdf)
except Exception as e:
print(f"发生错误: {e}")
使用示例
假设你有一个包含 .webp
图片的文件夹,路径为 C:\Images\
,希望将这些图片保存为 output.pdf
文件。只需要将代码中的 folder_path
和 output_pdf
修改为实际的路径即可:
folder_path = r"C:\Images"
output_pdf = "output.pdf"
运行代码后,你会在当前目录下看到生成的 PDF 文件。