本文介绍在 pycups 中通过 ppd 属性(如 `pageregion`、imageablearea 和 margins)精确控制自定义纸张尺寸的打印区域与边距,弥补 pagesize 单一设置的局限性。
在 PyCUPS 中,仅通过 PageSize 选项(如 "720x432")可定义物理纸张尺寸,但无法直接设置内容打印区域的边距——因为 PageSize 仅影响纸张大小,实际可打印区域(即 ImageableArea)和页边距(Margins)由打印机驱动(PPD 文件)中的底层属性控制。PyCUPS 并未暴露高级边距 API,因此需借助 PPD 属性覆盖机制,通过 printFile() 的 options 参数传入标准 CUPS PPD 关键字。
✅ 正确做法:使用 PageRegion + ImageableArea 控制有效打印区域PageRegion 定义物理纸张尺寸(单位:points),ImageableArea 定义左下角坐标 (llx, lly) 与右上角坐标 (urx, ury),二者共同决定内容可绘制区域,等效于设置上下左右边距。
例如:设定 10×6 英寸纸张(720×432 points),并预留 0.25 英寸(18 points)边距:
import cups
def print_with_margins(printer_name, file_path, width_inch=10, height_inch=6, margin_inch=0.25):
conn = cups.Connection()
# 转换为 points (1 inch = 72 points)
w_pt = int(width_inch * 72)
h_pt = int(height_inch * 72)
m_pt = int(margin_inch * 72)
# PageRegion: 物理纸张尺寸
page_region = f"{w_pt}x{h_pt}"
# ImageableArea: [llx lly urx ury] — 左下和右上坐标
imageable = f"[{m_pt} {m_pt} {w_pt - m_pt} {h_pt - m_pt}]"
options = {
'PageSize': page_region,
'PageRegion': page_region,
'ImageableArea': imageable,
'cupsPrintQuality': '3' # 可选:3=高精度
}
job_id = conn.printFile(printer_name, file_path, "Print with Margins", options)
print(f"Job {job_id} printed on '{printer_name}' with {margin_inch}\" margins.")
# 使用示例
print_with_margins(
printer_name="TVS_MSP-250CH-TVS-original",
file_path="/home/tk/Documents/bill.txt",
width_inch=10,
height_inch=6,
margin_inch=0.25 # 左/右/上/下均为 0.25 英寸
)# 查询当前打印机的可用 PPD 属性
attrs = conn.getPrinterAttributes(printer_name)
if 'page-region-supported' in attrs:
print("PageRegion supported")
if 'imageable-area-supported' in attrs:
print("ImageableArea supported")通过合理组合 PageRegion 与 ImageableArea,你即可在任意 PyCUPS 打印任务中实现精准、跨设备一致的边距控制,无需依赖特定驱动扩展或外部工具。