简体   繁体   中英

How to have multiple text colors within the same paragraph in ReportLab?

I would like to create a paragraph as follows:

step = str(StepNumber) #StepNumber is an int

if flag == True:
    color = "green" 
    sv = "[S]"

else:
    color = "red" 
    sv = "[V]"


P = Paragraph('<font color = "black>step</font>' + '<font color = color>sv</font>', style)

This doesn't work and puts the XML string into the report rather than applying it to the step and sv parameters. The goal is to have the step number in black font and the sv parameter in green or red font (depending on the if statement above) within the same paragraph. I tried to put these into two separate paragraphs but this seems to add undesired new lines (or spacing, not sure) between the two paragraphs.

Also how can XML be used within a paragraph when a paragraph requires a style parameter which will already specifies its own font attributes (such as font color)?

The reason it is printed as XML is because you supply exactly that. So we have to format the string correctly as follows:

step = str(StepNumber)  # StepNumber is an int

if flag:
    color = "green"
    sv = "[S]"
else:
    color = "red"
    sv = "[V]"

P = Paragraph('<font color="black">{step}</font> <font color="{color}">{sv}</font>'.format(color=color, sv=sv, step=step)
    , style)

Now the string exactly depends on your variables and the XML is valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM