How to add bold and normal text in one line using drawString method in reportlab (python) How to add bold and normal text in one line using drawString method in reportlab (python) python python

How to add bold and normal text in one line using drawString method in reportlab (python)


You could use the setFont method of the canvas object, to set the font to Bold when needed, and Normal otherwise.

* UPDATE *

In order to calculate the right value for x, you can use the stringWidth method, that calculates the length of the string given its content, the font name and the font size. You will have to import it from reportlab.pdfbase.pdfmetrics:

[...]from reportlab.pdfbase.pdfmetrics import stringWidth[...]# student name variable.student_name = 'Alex'# Content.line1 = " is working on college project."line2 = "Reportlab is very good lib, "line3 = " liked it"# drawString location calculation.x = 0y = 8.5 * 72# First string.can.setFont('Helvetica-Bold', 8)can.drawString(x, y, student_name)can.setFont('Helvetica', 8)textWidth = stringWidth(student_name, 'Helvetica-Bold', 8) x += textWidth + 1can.drawString(x, y, line1)y = y - 72# Second String.x = 0can.setFont('Helvetica', 8)can.drawString(x, y, line2)textWidth = stringWidth(line2, 'Helvetica', 8) x += textWidth + 1can.setFont('Helvetica-Bold', 8)can.drawString(x, y, student_name)textWidth = stringWidth(student_name, 'Helvetica-Bold', 8) x += textWidth + 1can.setFont('Helvetica', 8)can.drawString(x, y, line3)# Create PDF.can.save()

Or you could have a look at ParagraphStyle and Paragraph (from reportlab.lib.styles import ParagraphStyle, from reportlab.platypus import Paragraph) but I am not sure if you can concatenate two different styles in the same string.


I found a way to format the Paragraph text with XML tags. Firstly you need to register the font family then it should work. Below I downloaded a group of .ttf files as an example and registered them, after that, the XML tags worked properly.

from reportlab.pdfbase import pdfmetricsfrom reportlab.pdfbase.ttfonts import TTFontfrom reportlab.pdfbase.pdfmetrics import registerFontFamilypdfmetrics.registerFont(TTFont('OpenSansR', 'OpenSans-Regular.ttf'))pdfmetrics.registerFont(TTFont('OpenSansL', 'OpenSans-Light.ttf'))pdfmetrics.registerFont(TTFont('OpenSansB', 'OpenSans-Bold.ttf'))registerFontFamily('OpenSans', normal='OpenSansR', bold='OpenSansB', italic='OpenSansL', boldItalic='OpenSansB')