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

如何解决ReportLab生成PDF时水印短文本偏移无法居中问题?

问题分析与解决方案

你的代码核心问题是对drawCentredString方法的理解偏差:该方法的第一个参数x本身就是文本的中心横坐标,但你额外减去了文本宽度的一半,相当于把文本中心往左偏移了半个文本宽度,导致短文本视觉上严重偏右;长文本因宽度较大,偏移量刚好抵消了部分误差,才看似正常。

修正方案1:保留原平移逻辑,修正坐标计算

from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4

text = "test test test"
# text = "Peter Schmidt, Musterstraße 1, 50767 Köln"
pdf = canvas.Canvas("watermark.pdf", pagesize=A4)

# 平移坐标系原点到(1inch, 1inch)(原坐标系左下角往上、往右各1英寸)
pdf.translate(inch, inch)
pdf.setFillColor(colors.grey, alpha=0.6)
pdf.setFont("Helvetica", 15)

# 计算平移后坐标系下的页面中心横坐标
page_width = A4[0]
center_x = (page_width / 2) - inch
# y坐标:距离平移后原点向下45点,即距离页面底部约27点(72-45)
pdf.drawCentredString(center_x, -45, text)

pdf.save()

修正方案2:取消平移,直接使用绝对坐标(更直观)

from reportlab.pdfgen import canvas
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4

text = "test test test"
# text = "Peter Schmidt, Musterstraße 1, 50767 Köln"
pdf = canvas.Canvas("watermark.pdf", pagesize=A4)

pdf.setFillColor(colors.grey, alpha=0.6)
pdf.setFont("Helvetica", 15)

page_width, _ = A4
# 页面中心横坐标
center_x = page_width / 2
# 距离页面底部的垂直距离(可按需调整)
bottom_offset = 27

pdf.drawCentredString(center_x, bottom_offset, text)

pdf.save()

关键说明

  • drawCentredString会自动以传入的x值为中心对齐文本,无需手动计算文本宽度调整坐标;
  • 方案2去掉了容易混淆的坐标系平移,直接基于PDF原始坐标系(左下角为(0,0),x轴向右、y轴向上)计算位置,更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 04:32:36