You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用coustom_PDF生成PDF后无法调用打印机打印问题咨询

问题原因排查
  • os.startfile(temp_file, 'print')是Windows平台专属API,仅在Windows环境下生效,且依赖系统默认PDF应用的print动作关联配置,若系统未设置默认PDF阅读器、或阅读器未关联打印指令,该调用会静默失败
  • tempfile.mktemp()已被官方废弃,且未对临时文件做存活校验,文件生成后可能被系统自动清理,导致打印时找不到目标文件
  • PDF输出操作未做缓冲区刷新/句柄释放逻辑,调用pdf.output()后立即触发打印,会出现文件被程序占用无法被打印服务读取的问题
  • 非功能影响提示:代码中emphasize_data填写的匹配字符串是Abdul Wahab,但测试数据里对应值为Abdul Wahaab(多了一个a),高亮效果会不生效;表头的月份拼写也存在少量错误,可按需调整
修复后可用代码
import os
import tempfile
import time
import platform
import subprocess
import coustom_PDF

def print_from_printer(form_Heading, Chart_heder, lists):
    # 替换废弃的mktemp,生成临时文件且关闭后不自动删除
    with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as tf:
        temp_file = tf.name

    try:
        pdf = coustom_PDF()
        pdf.add_page()
        pdf.set_font("Times", size=11)

        wirth_cell = [20, 15, 10, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13]
        pdf.create_table(table_header=list(Chart_heder), table_data = list(lists), title=form_Heading, title_size=20, cell_width=wirth_cell, data_size=10, align_data='C', x_start='C', emphasize_data=["Abdul Wahaab", "p"], emphasize_color = (0, 0, 255))
        pdf.ln()
        pdf.output(temp_file)
        # 等待文件写入完成、释放句柄
        time.sleep(0.5)
        print(f"生成临时PDF文件:{temp_file}")

        # 跨平台打印适配,兼容性比os.startfile更稳定
        system_platform = platform.system()
        if system_platform == 'Windows':
            subprocess.run(['start', '/WAIT', 'print', temp_file], shell=True, check=True)
        elif system_platform == 'Darwin': # macOS
            subprocess.run(['lp', temp_file], check=True)
        elif system_platform == 'Linux':
            subprocess.run(['lp', temp_file], check=True)
        else:
            print(f"不支持的系统:{system_platform}")
    finally:
        # 不需要保留生成的PDF可打开下方注释,自动清理临时文件
        # os.unlink(temp_file)
        pass

heding = f'                  School Name or Date\n                      |Fess Chart Of Class 10|'
he = ("First_Name", 'Roll_No', 'Class', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Des')
data = [
    ['Abdul Wahaab', '1234', '10', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'],
    ['Abdul Hadi', '1234', '10', '0', '0', '0', '0', '0', '0', '0', '0', '0','0', '0', '0']
]
print_from_printer(form_Heading=heding, Chart_heder=he, lists=data)
额外校验点
  • 先确认Windows系统已经设置了默认PDF阅读器(比如Edge、Adobe Reader),手动右键任意PDF文件选择「打印」可以正常触发打印流程
  • 确认目标打印机已经连接正常、处于在线状态

内容的提问来源于stack exchange,提问作者Abdul Wahab Rana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:06:03