python 长截图拆分并转化为pdf

        在学习时,希望能够将微信推文转换为pdf方便导入笔记软件进行学习,但网上没有找到特别好用的转换方法。我想到可以通过将微信推文进行截图转PDF实现,但长截图转pdf后很容易只有一个pdf页面,在笔记软件中看不清楚,而逐页面截图又太麻烦,所以我先对微信推文进行长截图,之后用代码将其拆分为一个个页面再进行转换,效果还不错。代码如下:

 

from PIL import Image
import os
import img2pdf

path_file=r"文件路径"
#读取文件
img=Image.open(path_file)
#拆分路径方便后续保存
path,file=os.path.split(path_file)
file=os.path.splitext(file)[0]
os.mkdir(path+r"\result")
width,height=img.size
#当图片不为长截图时不进行拆分转换
if height<=1.5*width and width<=1.5*height:
    print("无需裁剪")
    exit(0)
Top_left_x=0
Top_left_y=0
dx=0
dy=0
#这里是希望能实现横向图片拆分,但横向拆分未经过试验
#是否旋转
is_rotate=0
if width<height:
    Bottom_right_x=width
    Bottom_right_y=1.5*width
    dy=1.5*width
else:
    Bottom_right_x=1.5*height
    Bottom_right_y=height
    dx=1.5*height
    is_rotate=1

count=0
id=0
imgs_list=[]
#逐个拆分保存为图片
while(True):
    id+=1
    rect=(Top_left_x,Top_left_y,Bottom_right_x,Bottom_right_y)
    crop=img.crop(rect)
    # crop.show()
    #如果是横向拆分,则旋转90度
    if is_rotate==1:
        crop=crop.rotate(90,expand=True)
    crop.save(path+r"\result\img"+f'{id}.jpg')
    imgs_list.append(path+r"\result\img"+f'{id}.jpg')
    if count==1:
        break
    Top_left_x += dx
    Top_left_y += dy
    Bottom_right_x += dx
    Bottom_right_y += dy
    if Bottom_right_x>=width and Bottom_right_y>=height and count==0:
        Bottom_right_x=width
        Bottom_right_y=height
        count=1
# imgs=[Image.open(p)for p in imgs_list]
#页面设置,设置宽为200,高为300
likeA4=(img2pdf.mm_to_pt(200),img2pdf.mm_to_pt(300))
layout=img2pdf.get_layout_fun(likeA4)

pdf_bytes=img2pdf.convert([i for i in imgs_list],layout_fun=layout)
pdf_bytes.__add__(pdf_bytes)
#写入文件
with open(path + r"\result\i"+f'{file}.pdf', 'ab+') as f:
    f.write(pdf_bytes)
    f.close()

注:代码中设定的裁剪比例为2:3,设置的pdf页面大小为200,300,最后会生成一个result文件夹,文件夹会与长截图在一个文件夹中,result中会有拆分好的图片和合并好的pdf,pdf名称与输入的名称一致,只是后缀变为了pdf。代码虽然考虑了横向拆分的情况,但是由于我暂时没有这个需求,所以并没有对横向拆分进行测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又菜又爱编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值