Python把扫描全能王生成的图片合成pdf

平时经常采用扫描全能王扫描文件,但没有会员,就会在右下角放一个二维码广告,后来有人告诉我,可以导出图片再打印出来,就不会存在二维码广告,我尝试,果真如此。但是每一次要一张张图片打印比较麻烦,有没有办法把图片合成pdf打印呢?上源码:

# -*- coding: utf-8 -*-
"""
Created on Sun Feb  4 14:49:19 2024

@author: YBK
"""

from PIL import Image
import os
import glob

# 防止字符串乱码
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

# 转化图片为统一宽度、高度
def resize_images(input_dir, output_dir, width, height):
    for filename in glob.glob(os.path.join(input_dir, '*.jpg')):  # 假设处理的是jpg图片,你可以根据需要修改文件扩展名
        image = Image.open(filename)
        kgb = image.width / image.height # 图片的宽高比
        bzkgb = width / height # 要转化图片的宽高比
        paste_w = 0 #粘贴图片在画布上的位置,以左上角为原点 初设x为0
        paste_h = 0 #初设y为0
        if kgb <= bzkgb:
            resized_image = image.resize((int(image.width * (height / image.height)), height)) # 保持宽高比,根据高度调整宽度
            paste_w = int((width - int(image.width * (height / image.height))) / 2)
        else:
            resized_image = image.resize((width, int(image.height * (width / image.width))))  # 保持宽高比,根据宽度调整高度
            paste_h = int((height - int(image.height * (width / image.width))) / 2)
        canvasnew = Image.new('RGB', (width, height), 'white') #创建一块画布        
        canvasnew.paste(resized_image, (paste_w, paste_h)) # 居中粘贴图片
        output_path = os.path.join(output_dir, os.path.basename(filename))
        image.close()
        canvasnew.save(output_path)  # 保存调整尺寸后的图片
        canvasnew.close()


# 转换为pdf
def pic2pdf(img_path, pdf_path, replacestr):
    file_list = os.listdir(img_path)
    sources = []
    jpg_files = []
    for file in file_list:
        if 'png' in file or 'jpg' in file:
            jpg_files.append(file)
    
    jpg_files.sort(key=lambda x: int(x.replace(replacestr,'').split('.')[0]))
    output = Image.open(img_path + jpg_files[0])
    jpg_files.pop(0)
    for file in jpg_files:
        jpg_file = Image.open(img_path + file)
        if jpg_file.mode == "RGB":
            jpg_file = jpg_file.convert("RGB")
        sources.append(jpg_file)
    output.save(pdf_path, "pdf", save_all=True, append_images=sources)


# 待转换图像路径
img_path = r"E:\图片路径"+'\\'
# 转换后的pdf
pdf_path = r"E:\保存pdf路径\生成.pdf"

resize_images(img_path, img_path, 1980, 2800) # 打印A4纸210*297 按这个比例图片是1980*2800
pic2pdf(img_path=img_path, pdf_path=pdf_path, replacestr='图片文件的前缀_')

图片宽高比转化过程的思路:

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值