基于Python优化文件夹内标签打印:实现每页6张合并打印
优化标签打印代码:实现每页6张合并打印,减少纸张浪费
现有代码仅逐个打印单个标签文件,会导致每张标签占用一页纸张,造成不必要的浪费。要实现每页打印6张标签的效果,我们可以通过将多个标签文件合并为单页布局的PDF来解决,以下是具体优化方案:
前提准备
先安装所需依赖库:
pip install PyPDF2 reportlab
优化后的代码
import os import tkinter as tk from tkinter import filedialog from PyPDF2 import PdfReader from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter def menu(): print("1- 重试") print("0- 退出") while True: opt = input("选择操作选项: ") try: opt_int = int(opt) if opt_int in (0, 1): return opt_int except ValueError: input("输入无效,按回车重试...") def create_combined_pdf(input_files, output_path): # 采用Letter纸张尺寸,设置2列3行的6标签布局 page_width, page_height = letter # 边距与标签尺寸配置,可根据实际标签大小调整 margin = 20 label_width = (page_width - 3 * margin) / 2 label_height = (page_height - 4 * margin) / 3 # 创建新PDF画布 c = canvas.Canvas(output_path, pagesize=letter) current_x = margin current_y = page_height - margin - label_height count = 0 for file_path in input_files: try: reader = PdfReader(file_path) # 读取标签PDF的第一页 label_page = reader.pages[0] # 计算缩放比例,确保标签适配预设尺寸 orig_w, orig_h = float(label_page.mediabox.width), float(label_page.mediabox.height) scale = min(label_width/orig_w, label_height/orig_h) scaled_w, scaled_h = orig_w*scale, orig_h*scale # 居中放置标签 x_offset = (label_width - scaled_w)/2 y_offset = (label_height - scaled_h)/2 c.drawImage(file_path, current_x+x_offset, current_y+y_offset, width=scaled_w, height=scaled_h) count += 1 # 切换标签位置:先列后行 if count % 2 == 0: current_x = margin current_y -= label_height + margin else: current_x += label_width + margin # 满6个标签则新建一页 if count % 6 == 0: c.showPage() current_x = margin current_y = page_height - margin - label_height except Exception as e: print(f"警告:处理文件 {os.path.basename(file_path)} 失败 - {str(e)}") c.save() def main(): while True: root = tk.Tk() root.withdraw() path = filedialog.askdirectory() if not path: print("未选择文件夹。") opt = menu() if opt == 0: break continue # 筛选文件夹内的PDF标签文件(可根据实际格式修改扩展名) label_files = [] for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isfile(file_path) and file.lower().endswith('.pdf'): label_files.append(file_path) if not label_files: print("文件夹内未找到PDF标签文件。") opt = menu() if opt == 0: break continue # 生成合并后的PDF文件 combined_pdf = os.path.join(path, "combined_labels.pdf") print("正在合并标签文件...") create_combined_pdf(label_files, combined_pdf) print(f"合并完成,生成文件:{combined_pdf}") # 打印合并后的PDF try: os.startfile(combined_pdf, 'print') print("正在打印合并后的标签...") except Exception as e: print(f"警告:打印合并文件失败 - {str(e)}") break print("任务完成!") if __name__ == "__main__": main()
代码说明
- 布局配置:默认采用Letter纸张,设置2列3行的布局,可通过调整
margin、label_width、label_height参数适配不同尺寸的标签和纸张。 - 文件兼容:当前仅处理PDF格式标签,若你的标签是图片格式,可修改文件扩展名判断逻辑,并调整
drawImage的参数适配。 - 合并逻辑:自动将标签按布局排列,满6个标签自动新建页面,避免单页单标签的纸张浪费。
- 打印流程:仅打印合并后的单个PDF文件,大幅减少打印次数和纸张消耗。
内容的提问来源于stack exchange,提问作者Ezequiel Rodríguez
相关产品推荐
相关产品推荐

