Frage

Hy,

I am using report lab for pdf generation. I want to draw a text, which is a Paragraph, representing a title, so, if the title is longer than the paragraph's available wifth it will split on the next line and if the title is to long to fit in paragraph's available width and height than the text will be resized.

It is working ok with a amaller font of 10, but, If I choose a style with a bigger font, like:

title_style = ParagraphStyle("title", fontName='Helvetica', fontSize=50, alignment=TA_CENTER, backColor=None)

than the text is drawn like in the image below, the words are overlapping: sample image

here is my code:

def draw_on(canvas, x, y, paragraph, style, text, available_width, available_height, min_font_size=8):
    w, h = paragraph.wrap(available_width, available_height)
    temp_font_size = paragraph.style.fontSize

    while temp_font_size > min_font_size:

        if w <= available_width and h <= available_height:
            paragraph.drawOn(canvas, x, y)
            break
        else:

            temp_font_size -= 1
            style.fontSize = temp_font_size
            paragraph = Paragraph(text, style)
            w, h = paragraph.wrap(available_width, available_height)



def generate_pdf():

    c = canvas.Canvas("FirstPage.pdf")

    title_style = ParagraphStyle("title", fontName='Helvetica', fontSize=10, alignment=TA_CENTER, backColor=None)

    title_text = 'If title has a small font, everything s ok.'
    title_paragraph = Paragraph(title_text, title_style)
    title_paragraph_available_width = 2*inch
    title_paragraph_available_height = 1*inch
    title_min_font_size = 8

    draw_on(c, 2*inch, 5*inch, title_paragraph, title_style, title_text, title_paragraph_available_width,
            title_paragraph_available_height, title_min_font_size)


    c.showPage()
    c.save()

Anyone has an ideea why that is happening and how to fix that?

War es hilfreich?

Lösung

This is described on page 67 of the userguide:

The fontSize and fontName tags are obvious, but it is important to set the leading. This is the spacing between adjacent lines of text; a good rule of thumb is to make this 20% larger than the point size.

So in your case you need have to add leading = 50 * 1.2 to your ParagraphStyle

Also, as a side note, i would advise you to either use the full potential of reportlabs Platypus (Paragraph's, etc.) or just stick with reportlabs pdfgen, which is more basic and easy to code. Platypus is good for longer texts and relative positioning (think latex) and pdfgen is more for absolute positioning (word). But this is just my oppinion...

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top