Python小工具,长图另存为pdf

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xvshu/article/details/82804177

在网上了一个长的图片,结果发现没有一个合适的工具,将长图先批量截取为4:3格式,存储到指定地点,然后存储为pdf

代码:

from reportlab.lib.pagesizes import portrait
from reportlab.pdfgen import canvas
import os
from PIL import Image

# 按照3:4 分割图片,返回图片存储结果集
def splitimage(src, dstpath):
    img = Image.open(src)
    w, h = img.size
    height=w*4/3 #3:4比例出的高度,等比缩放,算出高度
    height_dim = w*4/3 # 记录一个固定值,方便后期调用
    print(height)
    num=h/height# 分割次数
    print(num)
    index=0

    s = os.path.split(src)#分割出路径和文件名
    if dstpath == '':
        dstpath = s[0]
    fn = s[1].split('.')
    basename = fn[0]#文件名
    postfix = fn[-1]#后缀名
    img_urls=[]

    while (index < num):
        print('Index is:', index," Height is ",height)
        box = (0, height-height_dim, w, height)
        img.crop(box).save(os.path.join(dstpath, basename + '_' + str(index) + '.' + postfix), img.format)
        img_urls.append(os.path.join(dstpath, basename + '_' + str(index) + '.' + postfix))
        height = height+height_dim
        index = index + 1
    return img_urls

# 零散,大小一致图片,存储为pdf
def imgtopdf(input_paths, outputpath):
    index=0
    # 取一个大小
    (maxw, maxh) = Image.open(input_paths[0]).size
    c = canvas.Canvas(outputpath, pagesize=portrait((maxw, maxh)))
    for ont_path in input_paths :
        c.drawImage(ont_path, 0, 0, maxw, maxh)
        c.showPage()
        index=index+1
    c.save()



src="D:\\xvshu\\高数\\线性代数资料\\测试.png"
dstpath="D:\\xvshu\\高数\\线性代数资料\\"
imgs = splitimage(src, dstpath)
print(imgs)

# 调用demo:
imgtopdf(imgs, "D:\\xvshu\\高数\\线性代数资料\\测试.pdf")
print("over")


猜你喜欢

转载自blog.csdn.net/xvshu/article/details/82804177
今日推荐