关于 data-export-pdf
使用 reportlab 在本地生成 PDF 报告的技能,适用于分析总结、表格、图表和文档导出。提供文档排版示例及页面布局、图片和表格处理建议。
主要功能
- 01生成含文本的 PDF 报告
- 02插入格式化表格与图表
- 03自定义页眉页脚和多栏布局
- 04提供页面与图片排版建议
适用场景
- 01导出包含 QC 指标的报告
- 02汇总差异表达基因结果
- 03将分析图表与说明合并为 PDF
- 04制作出版用补充材料
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ omicverse/ omicverse --skill data-export-pdf安装后在 Claude Code 中输入/data-export-pdf确认已加载。
详细介绍
PDF 报告生成(通用)
概述
此技能可帮助你创建专业的 PDF 报告,其中包含分析摘要、格式化表格和嵌入式可视化图表。与托管在云端的解决方案不同,此技能使用 reportlab Python 库,并在你的环境中本地运行,因此兼容 所有 LLM 提供商,包括 GPT、Gemini、Claude、DeepSeek 和 Qwen。
何时使用此技能
- 生成包含文本和表格的分析报告
- 创建嵌入绘图的摘要 PDF
- 导出格式化文档
- 制作可供发表的补充材料
- 将多项分析结果合并到单个文档中
使用方法
第 1 步:导入所需库
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, Image
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from datetime import datetime
import matplotlib.pyplot as plt
第 2 步:创建基本 PDF 文档
# Create PDF file
pdf_filename = "analysis_report.pdf"
doc = SimpleDocTemplate(pdf_filename, pagesize=letter)
story = [] # Container for PDF elements
# Get default styles
styles = getSampleStyleSheet()
title_style = styles['Title']
heading_style = styles['Heading1']
normal_style = styles['Normal']
# Add title
story.append(Paragraph("Analysis Report", title_style))
story.append(Spacer(1, 0.2*inch))
# Add date
date_text = f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}"
story.append(Paragraph(date_text, normal_style))
story.append(Spacer(1, 0.3*inch))
# Build PDF
doc.build(story)
print(f"✅ PDF saved to: {pdf_filename}")
第 3 步:添加文本内容
story = []
# Title
story.append(Paragraph("Single-Cell RNA-seq Analysis Report", title_style))
story.append(Spacer(1, 0.2*inch))
# Section heading
story.append(Paragraph("1. Overview", heading_style))
story.append(Spacer(1, 0.1*inch))
# Paragraph text
overview_text = """
This report summarizes the single-cell RNA-seq analysis performed on the dataset.
The analysis includes quality control, normalization, dimensionality reduction,
clustering, and cell type annotation.
"""
story.append(Paragraph(overview_text, normal_style))
story.append(Spacer(1, 0.2*inch))
第 4 步:添加表格
# Prepare table data
table_data = [
['Metric', 'Value'], # Header
['Total Cells', '5,000'],
['Total Genes', '20,000'],
['Mean Genes/Cell', '2,500'],
['Median UMIs/Cell', '10,000']
]
# Create table
table = Table(table_data, colWidths=[2.5*inch, 2*inch])
# Style table
table.setStyle(TableStyle([
# Header styling
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 12),
# Body styling
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
('GRID', (0, 0), (-1, -1), 1, colors.black),
('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
('FONTSIZE', (0, 1), (-1, -1), 10),
]))
story.append(table)
story.append(Spacer(1, 0.3*inch))
第 5 步:嵌入图像/绘图
# Save matplotlib figure first
fig, ax = plt.subplots(figsize=(6, 4))
# ... create your plot ...
plot_filename = "temp_plot.png"
fig.savefig(plot_filename, dpi=150, bbox_inches='tight')
plt.close(fig)
# Add image to PDF
story.append(Paragraph("2. UMAP Visualization", heading_style))
story.append(Spacer(1, 0.1*inch))
img = Image(plot_filename, width=4*inch, height=3*inch)
story.append(img)
story.append(Spacer(1, 0.2*inch))
完整示例:分析报告
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image
from datetime import datetime
import matplotlib.pyplot as plt
import pandas as pd
def create_analysis_report(adata, output_path="analysis_report.pdf"):
"""Create comprehensive PDF analysis report"""
# Initialize PDF
doc = SimpleDocTemplate(output_path, pagesize=letter)
story = []
styles = getSampleStyleSheet()
# Title
story.append(Paragraph("Single-Cell RNA-seq Analysis Report", styles['Title']))
story.append(Spacer(1, 0.2*inch))
story.append(Paragraph(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}", styles['Normal']))
story.append(Spacer(1, 0.3*inch))
# Overview
story.append(Paragraph("1. Dataset Overview", styles['Heading1']))
story.append(Spacer(1, 0.1*inch))
overview_data = [
['Metric', 'Value'],
['Total Cells', f'{adata.n_obs:,}'],
['Total Genes', f'{adata.n_vars:,}'],
['Observations', ', '.join(adata.obs.columns[:5].tolist())],
]
table = Table(overview_data, colWidths=[2.5*inch, 3.5*inch])
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('GRID', (0, 0), (-1, -1), 1, colors.black),
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
]))
story.append(table)
story.append(Spacer(1, 0.3*inch))
# Cluster distribution
if 'clusters' in adata.obs:
story.append(Paragraph("2. Cluster Distribution", styles['Heading1']))
story.append(Spacer(1, 0.1*inch))
cluster_counts = adata.obs['clusters'].value_counts().sort_index()
cluster_data = [['Cluster', 'Cell Count', 'Percentage']]
total_cells = adata.n_obs
for cluster, count in cluster_counts.items():
percentage = (count / total_cells) * 100
cluster_data.append([str(cluster), str(count), f'{percentage:.1f}%'])
table = Table(cluster_data, colWidths=[1.5*inch, 1.5*inch, 1.5*inch])
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('GRID', (0, 0), (-1, -1), 1, colors.black),
('BACKGROUND', (0, 1), (-1, -1), colors.lightblue),
]))
story.append(table)
story.append(Spacer(1, 0.3*inch))
# Visualization (if UMAP exists)
if 'X_umap' in adata.obsm:
story.append(Paragraph("3. UMAP Visualization", styles['Heading1']))
story.append(Spacer(1, 0.1*inch))
# Create UMAP plot
fig, ax = plt.subplots(figsize=(6, 5))
scatter = ax.scatter(
adata.obsm['X_umap'][:, 0],
adata.obsm['X_umap'][:, 1],
c=adata.obs['clusters'].astype('category').cat.codes if 'clusters' in adata.obs else 'blue',
s=5, alpha=0.5
)
ax.set_xlabel('UMAP1')
ax.set_ylabel('UMAP2')
ax.set_title('UMAP Projection')
plot_path = 'temp_umap.png'
fig.savefig(plot_path, dpi=150, bbox_inches='tight')
plt.close(fig)
img = Image(plot_path, width=5*inch, height=4*inch)
story.append(img)
# Build PDF
doc.build(story)
print(f"✅ PDF report saved to: {output_path}")
return output_path
# Usage
create_analysis_report(adata, "my_analysis_report.pdf")
最佳实践
- 页面大小:标准文档使用
letter(美国)或A4(国际) - 页边距:SimpleDocTemplate 默认页边距为 1 英寸;可使用
leftMargin、rightMargin等进行调整 - 图像:将 matplotlib 图形以 150-300 DPI 保存,以获得良好质量
- 表格:合理控制列数(为便于阅读,最多 4-6 列)
- 文件清理:创建 PDF 后删除临时图像文件
- 内存:对于大型文档,分段构建以管理内存
高级功能
自定义页眉/页脚
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
def add_header_footer(canvas_obj, doc):
canvas_obj.saveState()
# Header
canvas_obj.setFont('Helvetica', 9)
canvas_obj.drawString(inch, letter[1] - 0.5*inch, "Analysis Report")
# Footer
canvas_obj.drawString(inch, 0.5*inch, f"Page {doc.page}")
canvas_obj.restoreState()
doc = SimpleDocTemplate(pdf_filename, pagesize=letter)
doc.build(story, onFirstPage=add_header_footer, onLaterPages=add_header_footer)
多栏布局
from reportlab.platypus import Frame, PageTemplate
frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1')
frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2')
doc.addPageTemplates([PageTemplate(id='TwoCol', frames=[frame1, frame2])])
颜色编码表格
# Highlight significant results
for i, row in enumerate(deg_results):
if row['qvalue'] < 0.05:
table.setStyle(TableStyle([
('BACKGROUND', (0, i+1), (-1, i+1), colors.yellow)
]))
常见用例
QC 报告
qc_metrics = {
'Total Cells': adata.n_obs,
'Median Genes/Cell': int(adata.obs['n_genes'].median()),
'Median UMIs/Cell': int(adata.obs['n_counts'].median()),
'Mean Mito %': f"{adata.obs['percent_mito'].mean():.2f}%"
}
table_data = [['Metric', 'Value']] + [[k, str(v)] for k, v in qc_metrics.items()]
# ... create table as shown above
DEG 摘要表
# Top 10 upregulated genes
top_genes = deg_df.nlargest(10, 'log2FC')[['gene', 'log2FC', 'qvalue']]
table_data = [['Gene', 'log2FC', 'Q-value']]
for _, row in top_genes.iterrows():
table_data.append([row['gene'], f"{row['log2FC']:.2f}", f"{row['qvalue']:.2e}"])
故障排除
问题:“找不到 reportlab”
解决方案:
import subprocess
subprocess.check_call(['pip', 'install', 'reportlab'])
问题:“找不到图像”
解决方案:确保图像路径正确,且文件在添加到 PDF 之前已存在:
import os
if os.path.exists(plot_filename):
img = Image(plot_filename, width=4*inch, height=3*inch)
story.append(img)
问题:“表格超出页面宽度”
解决方案:缩小列宽或字体大小:
table = Table(data, colWidths=[1.5*inch, 1.5*inch, 2*inch])
table.setStyle(TableStyle([('FONTSIZE', (0, 0), (-1, -1), 8)]))
技术说明
- 库:使用
reportlab(纯 Python,支持广泛) - 执行:在 Agent 的沙盒中本地运行
- 兼容性:兼容所有 LLM 提供商(GPT、Gemini、Claude、DeepSeek、Qwen 等)
- 文件大小:以文本为主的 PDF 文件较小(<1MB);以图像为主的 PDF 文件可能为 5-20MB
- 性能:典型的报告生成耗时 1-3 秒
参考资料
- reportlab 文档:https://www.reportlab.com/docs/reportlab-userguide.pdf
- reportlab platypus 指南:https://www.reportlab.com/software/opensource/rl-toolkit/guide/
评论
支持 Markdown