如何用Python ReportLab Platypus左对齐PDF中的图片?
如何让ReportLab Platypus中的图片左对齐?
ReportLab Platypus的Image组件默认采用居中对齐,要将图片设置为左对齐,最直接的方式是在创建Image对象时指定hAlign参数为'LEFT'。
方法一:直接设置Image的hAlign属性
修改你代码中创建Image的行,添加hAlign='LEFT'参数:
parts.append(Image(img_path, 1*inch, 1*inch, hAlign='LEFT'))
hAlign支持三个可选值:'LEFT'(左对齐)、'CENTER'(默认居中)、'RIGHT'(右对齐),按需选择即可。
完整修改后的代码
from reportlab.lib.units import cm, inch from reportlab.lib.pagesizes import LETTER from reportlab.platypus import SimpleDocTemplate, Paragraph, Image from reportlab.lib.styles import getSampleStyleSheet text = "<b>BOLD</b> normal <br/><br/>" + \ " After newline <font color=red>red</font>" + \ " <font size=20>Larger</font> normal.<br/><br/>" new_pdf_path = "pdf_path" img_path = "img_path" doc = SimpleDocTemplate(new_pdf_path,pagesize=LETTER,rightMargin=1*inch,leftMargin=1*inch,topMargin=1*inch,bottomMargin=1*inch) parts = [] parts.append(Paragraph(text, getSampleStyleSheet()['Normal'])) # 设置图片左对齐 parts.append(Image(img_path, 1*inch, 1*inch, hAlign='LEFT')) doc.build(parts)
补充:复杂布局场景的替代方案
如果需要将图片和文本进行更复杂的混排(比如图片嵌入段落中),可以将Image对象包裹到Paragraph里,通过段落样式控制对齐:
from reportlab.platypus import Paragraph, Image from reportlab.lib.styles import ParagraphStyle # 创建左对齐的段落样式 left_align_style = ParagraphStyle(name='LeftAlign', alignment=0) # 0代表左对齐,1居中,2右对齐 # 将图片转为可嵌入段落的对象 img = Image(img_path, 1*inch, 1*inch) # 用Paragraph包裹并应用样式 parts.append(Paragraph(f'<img src="{img_path}" width="{1*inch}" height="{1*inch}"/>', left_align_style))
不过对于单纯的图片左对齐需求,第一种方法已经足够简洁高效。
内容的提问来源于stack exchange,提问作者user984003
相关产品推荐
相关产品推荐

