乐于分享
好东西不私藏

第四篇:PDF生成技术方案对比与实现

第四篇:PDF生成技术方案对比与实现

第四篇:《PDF生成技术方案对比与实现》

一、ReportLab vs WeasyPrint对比

特性 ReportLab WeasyPrint
语言 Python原生 HTML/CSS转PDF
中文支持 需配置字体 需配置字体
学习成本 中等 较低(HTML基础)
样式控制 代码级精确 CSS灵活
离线可用
批量生成

二、ReportLab中文配置实战

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# 中文字体注册
font_paths = [
    '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc',  # 文泉驿正黑
    '/usr/share/fonts/truetype/wqy/wqy-microhei.ttc',  # 文泉驿微米黑
]
for path in font_paths:
    if os.path.exists(path):
        pdfmetrics.registerFont(TTFont('ChineseFont', path))
        break

三、ReportLab简历生成完整代码

#!/usr/bin/env python3
"""
简历PDF生成器 - ReportLab实现
"""
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.lib.colors import HexColor, white
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER

# 颜色配置
PRIMARY = HexColor('#1a365d')   # 深蓝主色
ACCENT = HexColor('#3182ce')     # 亮蓝强调

def create_styles():
    styles = getSampleStyleSheet()

    # 姓名样式
    styles.add(ParagraphStyle(
        name='ResumeName',
        fontName='ChineseFont',
        fontSize=22,
        leading=28,
        alignment=TA_CENTER,
        textColor=PRIMARY,
    ))

    # 章节标题样式
    styles.add(ParagraphStyle(
        name='SectionTitle',
        fontName='ChineseFont',
        fontSize=13,
        leading=18,
        textColor=white,
        backColor=PRIMARY,
    ))

    return styles

def add_section_header(story, title, styles):
"""添加带背景色的章节标题"""
    story.append(Spacer(1, 6*mm))
    title_para = Paragraph(f" {title} ", styles['SectionTitle'])
    table = Table([[title_para]], colWidths=[170*mm])
    table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), PRIMARY),
        ('TOPPADDING', (0, 0), (-1, -1), 4),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
    ]))
    story.append(table)

def build_pdf(user_info, output_path):
"""生成简历PDF"""
    doc = SimpleDocTemplate(
        output_path,
        pagesize=A4,
        rightMargin=15*mm,
        leftMargin=15*mm,
        topMargin=12*mm,
        bottomMargin=12*mm,
    )

    styles = create_styles()
    story = []

    # 姓名
    story.append(Paragraph(user_info['name'], styles['ResumeName']))
    story.append(Paragraph(
        f"{user_info['title']} | {user_info['location']}",
        styles['ResumeBody']
    ))

    # 教育背景
    add_section_header(story, "教育背景", styles)
    story.append(Paragraph(
        f"<b>{user_info['school']}</b> {user_info['major']}{user_info['degree']}",
        styles['ResumeBody']
    ))

    doc.build(story)
    print(f"PDF已生成: {output_path}")

四、模板样式配置表

样式项 配置值 说明
页边距 15mm A4标准
标题字号 13px 章节标题
正文字号 10px 主要内容
行高 1.5 基础行高
标题背景色 #1a365d 深蓝主色
强调色 #3182ce 亮蓝

---
本文由AI辅助创作
作者:TJMtaotao
发表于:MEITUSTYLE