如何使用Python pycups为自定义页面尺寸设置打印边距
如何在pycups中设置打印边距
CUPS打印系统支持通过打印选项直接配置边距,常用的参数有两种设置方式,单位统一为点(1英寸=72点):
- 用
Margins一次性设置左、右、上、下四边边距,格式为空格分隔的四个数值 - 用
LeftMargin/RightMargin/TopMargin/BottomMargin单独设置每一边
修改后的代码示例
import cups def print_to_printer(printer_name, file_path, custom_width=10, custom_length=6, margins=(0.25, 0.25, 0.25, 0.25)): conn = cups.Connection() # 英寸转点(1英寸=72点) custom_width_points = str(int(custom_width * 72)) custom_length_points = str(int(custom_length * 72)) page_size_str = f"{custom_width_points}x{custom_length_points}" # 把输入的英寸边距转换成点 left_margin, right_margin, top_margin, bottom_margin = [str(int(m * 72)) for m in margins] # 构建打印选项,包含自定义尺寸和边距(二选一即可) print_options = { 'PageSize': page_size_str, # 方式1:一次性设置四边 'Margins': f"{left_margin} {right_margin} {top_margin} {bottom_margin}", # 方式2:单独设置每边,注释掉方式1后启用 # 'LeftMargin': left_margin, # 'RightMargin': right_margin, # 'TopMargin': top_margin, # 'BottomMargin': bottom_margin } print_job_id = conn.printFile(printer_name, file_path, "Print Job", print_options) print(f"打印任务 {print_job_id} 已发送到 {printer_name},自定义尺寸({custom_width}x{custom_length}英寸),边距{str(margins)}英寸") # 示例调用 printer_name = "TVS_MSP-250CH-TVS-original" # 替换为你的打印机名称 file_to_print = "/home/tk/Documents/bill.txt" # 替换为你的文件路径 custom_width = 10 # 自定义宽度(英寸) custom_length = 6 # 自定义长度(英寸) # 设置边距:左、右、上、下,单位英寸 print_to_printer(printer_name, file_to_print, custom_width, custom_length, margins=(0.5, 0.5, 0.3, 0.3))
注意事项
- 不同打印机支持的边距参数可能有差异,可通过以下代码查看打印机支持的所有选项:
conn = cups.Connection() printer_attrs = conn.getPrinterAttributes(printer_name) print(printer_attrs.get('cupsOptionSupported', []))
- 如果打印的是文本文件,注意文本本身的缩进不要和打印边距叠加,避免排版偏移。
内容的提问来源于stack exchange,提问作者kumar
相关产品推荐
相关产品推荐

