脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python自动化办公之图片转PDF的实现

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

2022-11-29 10:49Python 集中营 Python

实现图片转换成PDF文档的操作方法有很多,综合对比以后感觉fpdf这个模块用起来比较方便而且代码量相当少。所以本文将利用Python语言实现图片转PDF,感兴趣的可以了解一下

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

?
1
pip install fpdf

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

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

初始化PDF文档对象

?
1
PDF = FPDF()

关闭自动分页

?
1
PDF.set_auto_page_break(0)

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

?
1
path = r'C:/imgs'

遍历图片到数组

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

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

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

设置图片的宽度和高度

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

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

?
1
2
3
4
5
6
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文档

?
1
2
3
PDF.output(os.path.join(path, "图片文档.pdf"), "F")
 
print('图片到PDF转换完成!')

实现效果图

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

补充

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

下面是实现的示例代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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))

到此这篇关于Python自动化办公之图片转PDF的实现的文章就介绍到这了,更多相关Python图片转PDF内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/lwsbc/p/16142099.html

延伸 · 阅读

精彩推荐