Search code examples
pythondjangopython-3.xpdf-generationreportlab

python Reportlab two items in the same row on a Paragraph


I would like to align two text in the same row, on the left and on the right:

TEXT1 TEXT2

and in the same line left align an image and center a text:

IMAGE TEXT

How is it possible?

That's my code:

Story=[]

styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT))
styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))


ptext = '<font size=15><b>{0}</b></font>'.format("TITLE")
Story.append(Paragraph(ptext, styles["Center"]))

Story.append(Spacer(10, 20))

ptext = '<font size=10>TEXT1 </font>'
Story.append(Paragraph(ptext, styles["Normal"]))
Story.append(Spacer(1, 12))

ptext = '<font size=10>CODICE OPERATORE</font>'
Story.append(Paragraph(ptext, styles["Normal"]))

Story.append(Spacer(1, 12))
Story.append(Spacer(1, 12))



signature = os.path.join(settings.MEDIA_ROOT, user.attr.get("signature"))
im = Image(signature, 80, 80)
im.hAlign ='RIGHT'

ptext = '<font size=10>Firma</font>'

Story.append(Spacer(1, 12))
Story.append(Spacer(1, 12))

Story.append(Paragraph(ptext, styles["Right"]))
Story.append(Spacer(1, 12))
Story.append(im)

Story.append(PageBreak())

doc.build(Story)

Thank you


Solution

  • Use a Table. The table can have its own style and the items (Paragraph, Image, ...) can also have their own style, that way you can have differently aligned items within the table cells

    from reportlab.lib.pagesizes import A4
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Table
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.enums import TA_RIGHT
    
    styles = getSampleStyleSheet()
    style_right = ParagraphStyle(name='right', parent=styles['Normal'], alignment=TA_RIGHT)
    doc = SimpleDocTemplate("my_doc.pdf", pagesize=A4)
    Story=[]
    # here you add your rows and columns, these can be platypus objects
    tbl_data = [
        [Paragraph("Hello", styles["Normal"]), Paragraph("World (right)", style_right)],
        [Paragraph("Another", styles["Normal"]), Paragraph("Row (normal)", styles["Normal"])]
    ]
    tbl = Table(tbl_data)
    Story.append(tbl)
    doc.build(Story)
    

    Output: enter image description here