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

如何在Python中输出带格式控制台文本并同步导出为PDF

在Python中实现控制台彩色文本输出与同步PDF导出

核心思路

  • 控制台直接用ANSI转义序列输出就行,现代终端(Linux/macOS终端、Windows Terminal等)都能识别解析;
  • PDF生成得先把带ANSI格式的文本拆成「样式+内容」的片段,再把ANSI样式映射成PDF支持的格式(颜色、粗体/斜体等),最后逐段渲染到PDF里。

实现步骤与代码示例

1. 安装依赖

用reportlab来生成PDF,先装包:

pip install reportlab

2. 解析ANSI转义序列的工具函数

写个函数把带格式的文本拆成可处理的片段,比如把示例文本拆成「正常文本+红色粗体RED+正常文本+斜体ITALIC+正常文本」:

import re

def parse_ansi_text(text):
    # 匹配ANSI转义序列和对应文本的正则
    ansi_pattern = re.compile(r'(\033\[[0-9;]*m)(.*?)(?=\033\[|$)')
    segments = []
    # 默认初始样式
    current_style = {'color': 'black', 'bold': False, 'italic': False}
    
    # 处理开头不带ANSI的普通文本
    if not text.startswith('\033['):
        parts = text.split('\033[', 1)
        if parts[0]:
            segments.append((current_style.copy(), parts[0]))
        if len(parts) > 1:
            text = '\033[' + parts[1]
        else:
            return segments
    
    # 逐段解析带ANSI的内容
    for match in ansi_pattern.finditer(text):
        code_part, content = match.groups()
        codes = code_part.strip('\033[').strip('m').split(';')
        for code in codes:
            if code == '0':  # 重置所有样式
                current_style = {'color': 'black', 'bold': False, 'italic': False}
            elif code == '1':  # 粗体
                current_style['bold'] = True
            elif code == '3':  # 斜体
                current_style['italic'] = True
            elif code.startswith('3'):  # 前景色映射
                color_map = {
                    '30': 'black', '31': 'red', '32': 'green',
                    '33': 'yellow', '34': 'blue', '35': 'magenta',
                    '36': 'cyan', '37': 'white'
                }
                current_style['color'] = color_map.get(code, 'black')
        if content:
            segments.append((current_style.copy(), content))
    return segments

3. 整合控制台输出与PDF生成

from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch

def text_to_pdf(segments, output_path):
    doc = SimpleDocTemplate(output_path, pagesize=(8.5*inch, 11*inch))
    styles = getSampleStyleSheet()
    flowables = []
    
    for style, content in segments:
        # 把ANSI样式转成reportlab支持的HTML格式标签
        formatted_content = content
        if style['bold']:
            formatted_content = f'<b>{formatted_content}</b>'
        if style['italic']:
            formatted_content = f'<i>{formatted_content}</i>'
        if style['color'] == 'red':
            formatted_content = f'<font color="red">{formatted_content}</font>'
        # 要支持更多颜色或样式,在这里加对应的标签转换就行
        
        para = Paragraph(formatted_content, styles['BodyText'])
        flowables.append(para)
    
    doc.build(flowables)

# 测试用的带格式文本
ansi_text = "This text contains some \033[1;31mRED\033[0m and \033[3mITALIC\033[0m words."

# 1. 控制台输出(直接打印原文本即可)
print(ansi_text)

# 2. 解析文本片段
text_segments = parse_ansi_text(ansi_text)

# 3. 生成PDF
text_to_pdf(text_segments, "colored_text.pdf")

补充说明

  • 如果需要支持更多ANSI样式(比如背景色、下划线),只需要在解析函数里添加对应样式的识别,再在PDF生成函数里补充对应的标签转换;
  • 要是Windows系统用的是旧版命令提示符(cmd),可能不支持ANSI转义序列,换成Windows Terminal就能解决。

内容的提问来源于stack exchange,提问作者Gunnar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:40:17