FPDF Python添加页脚异常:页脚出现在新空白页顶部
问题解决:FPDF添加页脚时出现空白页的问题
问题根源
你直接在循环里用pdf.set_y(-15)添加页脚的方式,会在图片占据页面空间接近底部时触发FPDF的自动分页机制——因为set_y(-15)要求定位到页面底部往上15的位置,如果当前页面剩余空间不够,FPDF会自动新建一页,这时候新页的当前Y坐标是顶部,set_y(-15)就会把内容放在新页的底部区域(但新页是空的,看起来就像页脚在空白页顶部)。另外,FPDF的footer方法需要通过继承类重写才能生效,直接套用官网示例却没正确继承的话,也不会起作用。
解决方案
通过继承FPDF类重写footer方法来实现页脚,同时调整图片的布局,给页脚预留足够空间,避免触发不必要的分页。
修改后的完整代码
import cv2 as cv from fpdf import FPDF class MyPDF(FPDF): def __init__(self, show_footer=False, *args, **kwargs): super().__init__(*args, **kwargs) self.show_footer = show_footer # 控制是否显示页脚 def footer(self): if not self.show_footer: return # 设置页脚位置:距底部15单位 self.set_y(-15) self.set_font("Arial", "I", 8) # 居中显示页码 self.cell(0, 10, f'Page {self.page_no()}', 0, 0, 'C') def save_images_as_pdf(image_files, output_pdf, numberpage="off", deformation="off"): # 实例化自定义PDF类,根据numberpage参数设置是否显示页脚 pdf = MyPDF(show_footer=(numberpage == "on")) # 页脚预留高度(和footer里的set_y(-15)对应) footer_margin = 15 # 页面实际可用高度:减去页脚预留空间 available_page_height = 297 - footer_margin for i, img_file in enumerate(image_files): pdf.add_page() print(img_file) img = cv.imread(img_file) img_height, img_width, _ = img.shape img_ratio = img_width / img_height page_width, page_height = 190, available_page_height page_ratio = page_width / page_height if deformation == "on": fit_width, fit_height = page_width, page_height else: if img_ratio > page_ratio: fit_width = page_width fit_height = fit_width / img_ratio else: fit_height = page_height fit_width = fit_height * img_ratio x_offset = (210 - fit_width) / 2 # Y偏移:从顶部开始,居中显示图片,同时保证图片底部不会碰到页脚区域 y_offset = (297 - fit_height - footer_margin) / 2 pdf.image(img_file, x_offset, y_offset, fit_width, fit_height) pdf.output(output_pdf) print(f"PDF has been saved as {output_pdf}")
关键改动说明
- 自定义MyPDF类:继承FPDF并重写
footer方法,通过show_footer属性控制页脚开关,这是FPDF官方推荐的页脚实现方式,能自动在每一页底部渲染页脚,不会触发意外分页。 - 预留页脚空间:计算图片布局时,把页脚需要的15单位高度从页面总高度里扣除,确保图片不会占满到页面底部,避免和页脚区域冲突。
- 移除循环内的页脚代码:原来循环里添加页脚的逻辑会导致分页问题,现在交给自定义类的
footer方法自动处理。
内容的提问来源于stack exchange,提问作者Joseph Le Berre
相关产品推荐
相关产品推荐

