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

Python执行函数时如何将终端所有输出保存为PDF

将Python终端输出转换为PDF的几种方法

方法1:先保存为文本文件,再转换为PDF

步骤1:修改代码将输出写入文本文件

你可以调整函数,把输出内容同时写入文本文件和打印到终端:

def calculator(x,y):
    output_lines = [
        f"Summation between {x}  &  {y} is:  {x + y}",
        f"Subtraction between {x}  &  {y} is:  {x - y}",
        f"Division between {x}  &  {y} is:  {x / y}",
        f"Multiplication between {x}  &  {y} is:  {x * y}"
    ]
    # 写入文本文件
    with open("calc_output.txt", "w", encoding="utf-8") as f:
        f.write("\n".join(output_lines))
    # 打印到终端
    print("\n".join(output_lines))

calculator(5,6)

步骤2:将文本文件转为PDF

可以用以下工具完成转换:

  • pandoc(命令行工具):
    先安装pandoc,然后执行命令:
    pandoc calc_output.txt -o calc_output.pdf
    
  • LibreOffice(命令行模式):
    执行命令:
    libreoffice --headless --convert-to pdf calc_output.txt
    

方法2:直接在Python中生成PDF(使用fpdf2库)

这种方法无需额外转换步骤,直接从输出内容生成PDF:

步骤1:安装依赖库

pip install fpdf2

步骤2:修改代码生成PDF

from fpdf import FPDF

def calculator(x,y):
    output_lines = [
        f"Summation between {x}  &  {y} is:  {x + y}",
        f"Subtraction between {x}  &  {y} is:  {x - y}",
        f"Division between {x}  &  {y} is:  {x / y}",
        f"Multiplication between {x}  &  {y} is:  {x * y}"
    ]
    # 打印到终端
    print("\n".join(output_lines))
    
    # 创建PDF并添加内容
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    # 逐行添加到PDF
    for line in output_lines:
        pdf.cell(200, 10, txt=line, ln=True, align="L")
    # 保存PDF文件
    pdf.output("calc_output.pdf")

calculator(5,6)

方法3:捕获终端输出流再生成PDF

如果不想修改原calculator函数的打印逻辑,可以捕获终端的输出内容,再生成PDF:

步骤1:安装fpdf2库

pip install fpdf2

步骤2:编写捕获和转换代码

import sys
from io import StringIO
from fpdf import FPDF

# 原计算器函数(无需修改)
def calculator(x,y):
    print("Summation between", x, " & ",y, "is: ", x + y)
    print("Subtraction between", x, " & ", y, "is: ", x - y)
    print("Division between", x, " & ", y, "is: ", x / y)
    print("Multiplication between", x, " & ", y, "is: ", x * y)

# 捕获终端输出
original_stdout = sys.stdout
captured_output = StringIO()
sys.stdout = captured_output

# 调用函数
calculator(5,6)

# 恢复标准输出
sys.stdout = original_stdout
output_text = captured_output.getvalue()

# 生成PDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
for line in output_text.splitlines():
    pdf.cell(200, 10, txt=line, ln=True, align="L")
pdf.output("calc_output.pdf")

内容的提问来源于stack exchange,提问作者Nguyễn Khang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:47:28