下载字体:https://github.com/adobe-fonts/source-han-sans/releases
下载fpdf2
pip uninstall fpdf
pip install fpdf2
运行代码
from fpdf import FPDF
from fpdf.enums import XPos, YPos
# 创建 PDF 类
class BabyFeedingPDF(FPDF):
def header(self):
self.set_font("SourceHanSans", size=16)
self.cell(0, 10, "0~12个月宝宝喂养规划表", new_x=XPos.LMARGIN, new_y=YPos.NEXT, align="C")
self.ln(5)
def chapter_title(self, title):
self.set_font("SourceHanSans", size=12)
self.cell(0, 10, title, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
self.ln(2)
def chapter_body(self, body):
self.set_font("SourceHanSans", size=11)
self.multi_cell(0, 8, body)
self.ln()
# 初始化 PDF
pdf = BabyFeedingPDF()
pdf.add_font("SourceHanSans", fname="SourceHanSansCN-Regular.otf")
pdf.add_page()
pdf.set_auto_page_break(auto=True, margin=15)
# 表头内容
table_header = ["月龄", "奶类需求", "辅食情况", "每日饮食频率与建议"]
table_data = [
["0-4月", "母乳或配方奶为主(按需)", "不添加辅食", "喂奶 8~12 次/天,观察体重增长、排便情况"],
["4-6月", "母乳或配方奶为主(600~900ml)", "试探性辅食(米粉、水果/蔬菜泥)", "1次辅食(小量),继续按需奶喂养"],
["6-7月", "600~800ml 奶", "蔬菜泥、水果泥、蛋黄泥", "奶 4-5 次 + 辅食 1~2 次"],
["7-8月", "600~700ml 奶", "加入肉泥、鱼泥、豆腐等", "奶 4 次 + 辅食 2 次(早餐+午餐)"],
["8-9月", "500~700ml 奶", "可吃软饭、碎面、整蛋黄", "2~3 餐辅食 + 1 奶点"],
["9-10月", "500~600ml 奶", "多样主食、碎菜、肉类", "3 餐辅食 + 1~2 点心"],
["10-11月", "400~600ml 奶", "家庭软饭+细碎食物,鼓励抓握", "建立三餐 + 点心制,训练自主吃饭"],
["11-12月", "400~600ml 奶", "食物逐渐接近家庭饮食", "3 正餐 + 1~2 点心,逐步减少奶量,过渡到1岁饮食"],
]
# 表格绘制
pdf.set_font("SourceHanSans", size=10)
cell_widths = [22, 45, 50, 70]
# 表头
for i, heading in enumerate(table_header):
pdf.cell(cell_widths[i], 10, heading, border=1, align="C")
pdf.ln()
# 表格内容
for row in table_data:
y_before = pdf.get_y()
max_y = y_before
for i, datum in enumerate(row):
x = pdf.get_x()
y = pdf.get_y()
pdf.multi_cell(cell_widths[i], 8, datum, border=1)
max_y = max(max_y, pdf.get_y())
pdf.set_xy(x + cell_widths[i], y)
pdf.set_y(max_y)
# 添加说明部分
pdf.ln(5)
pdf.chapter_title(" 辅食添加顺序建议:")
pdf.chapter_body("1. 米粉 → 菜泥 → 水果泥 → 蛋黄 → 肉泥/鱼泥 → 豆腐/面条\n"
"2. 每添加一种辅食,观察3天,确认不过敏再继续添加新食物")
pdf.chapter_title(" 注意事项:")
pdf.chapter_body("• 1岁前不要添加盐、糖、调料、蜂蜜\n"
"• 食物必须软烂易吞咽,避免呛咳\n"
"• 鼓励宝宝坐着吃饭、抓握食物,培养进餐习惯")
# 输出 PDF
output_path = "0-12个月宝宝喂养规划.pdf"
pdf.output(output_path)
print("PDF 已生成:", output_path)
生成实例