侧边栏壁纸

python实现图片转PDF

2023年11月05日 284阅读 0评论 0点赞

code.png

安装img2pdf库

pip install img2pdf

实现图片转PDF功能代码

# -*- coding: utf-8 -*-
"""
# @FilePath     : r'办公\图片转pdf\main.py'
# @creationTime : 2023-11-05 10:03:17
# @Author           : 魔法师
# @E-mail           : 2782226338@qq.com
# @BlogLink     : bytesquadblog.cn
# @Motto        : No sailor skilled was ever made By sailing on a sea of jade.
# @Description:
        
"""
import os
import img2pdf



# Replace the directory path with the folder containing images to be converted
#记得修改图片所在的路径
directory_path = r"C:\Users\Tnas\Pictures"
# List all image files in the directory
image_files = [i for i in os.listdir(directory_path) if i.endswith(".jpg") or i.endswith(".png")]

# Convert each image file to a separate PDF file
for image_file in image_files:
    img_file_name = str(image_file).split('.')[0]
    with open(os.path.join(directory_path, image_file), "rb") as file:
        image_data = file.read()
    pdf_data = img2pdf.convert(image_data)
    # Write the PDF content to a file (make sure you have write permissions for the specified file)
    with open(f'./pdf/{img_file_name}' + ".pdf", "wb") as file:
        file.write(pdf_data)
        print(img_file_name,'转换完毕!')
0

—— 评论区 ——

博主关闭了当前页面的评论