平时经常采用扫描全能王扫描文件,但没有会员,就会在右下角放一个二维码广告,后来有人告诉我,可以导出图片再打印出来,就不会存在二维码广告,我尝试,果真如此。但是每一次要一张张图片打印比较麻烦,有没有办法把图片合成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='图片文件的前缀_')
图片宽高比转化过程的思路: