网络编程
位置:首页>> 网络编程>> Python编程>> Python自动化办公之图片转PDF的实现

Python自动化办公之图片转PDF的实现

作者:Python  发布时间:2023-07-24 21:29:07 

标签:Python,图片,PDF

安装的方式很常规,直接使用pip安装就行了。

pip install fpdf

将需要使用的三方模块导入进来

from fpdf import FPDF  # PDF文档对象操作库
import os  # 文件路径操作库

初始化PDF文档对象

PDF = FPDF()

关闭自动分页

PDF.set_auto_page_break(0)

设置需要转换的批量图片路径

path = r'C:/imgs'

遍历图片到数组

images = [i for i in os.listdir(path)]

设置多少张图片在PDF中占一页

NUM = int(input('参数设置: 请输入多少张图片占用一页: \n'))

设置图片的宽度和高度

width = int(input('参数设置: 请输入每张图片的宽度: \n'))
height = int(input('参数设置: 请输入每张图片的高度: \n'))

遍历图片并向文档中添加图片

for index, image in enumerate(images):
   if index == 0:
       PDF.add_page()
   elif index % NUM == 0:
       PDF.add_page()
   PDF.image(os.path.join(path, image), w=width, h=height)

保存PDF文档

PDF.output(os.path.join(path, "图片文档.pdf"), "F")

print('图片到PDF转换完成!')

实现效果图

Python自动化办公之图片转PDF的实现

补充

当然Python还能实现多张图片合并转PDF格式

下面是实现的示例代码


from PIL import Image
import os
import img2pdf

flag = False
while not flag:
   dirname = input("请输入图片文件夹所在路径(例如d:/wlzcool):")
   flag = os.path.exists(dirname)
   if not flag:
       print("图片文件夹所在路径不存在!")
saveflag = False
while not saveflag:
   savedirname = input("请输入目标图片文件夹所在路径(例如d:/wlzcool2):")
   saveflag = os.path.exists(savedirname)
   if not saveflag:
       print("图片文件夹所在路径不存在!")
       automakedir = input("是否自动创建对应文件夹?(是Y/否N):")
       if automakedir.strip().upper() == "Y":
           os.makedirs(savedirname)
           saveflag = True
files = os.listdir(dirname)
reductionFactor = int(input("请输入长宽压缩比(例如3):"))
if reductionFactor <= 0:
   reductionFactor = 3
isConvertBlack = input("是否输出黑白版本?(是Y/否N):").strip().upper() == "Y"
for fname in files:
   if not fname.endswith(".jpg"):
       continue
   path = os.path.join(dirname, fname)
   savePath = os.path.join(savedirname, fname)
   if os.path.isdir(path):
       continue
   img = Image.open(path)    
   if img.size[0] > img.size[1]:
       im_rotate = img.rotate(90, expand=True)
       size = (int(im_rotate.size[0] / reductionFactor), int(im_rotate.size[1] / reductionFactor))
       im_rotate = im_rotate.resize(size)
       if isConvertBlack:
           im_rotate = im_rotate.convert("L")
       im_rotate.save(savePath, quality=95)
   else:
       size = (int(img.size[0] / reductionFactor), int(img.size[1] / reductionFactor))
       img = img.resize(size)
       if isConvertBlack:
           img = img.convert("L")
       img.save(savePath, quality=95)
filename = input("请输入输出文件名(例如:第一章):")
with open(filename + ".pdf", "wb") as f:
   imgs = []
   files = os.listdir(savedirname)
   for fname in files:
       if not fname.endswith(".jpg"):
           continue
       path = os.path.join(savedirname, fname)
       if os.path.isdir(path):
           continue
       imgs.append(path)
   f.write(img2pdf.convert(imgs))

来源:https://www.cnblogs.com/lwsbc/p/16142099.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com