Center text in python

Asked

Viewed 6,781 times

2

Good afternoon, I’m creating a program to generate certificates, but I’m having trouble centralizing the names, how could I do that? For every name is of a size.

I tried the center(), but it didn’t work. Follow the code:

from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from reportlab.lib.pagesizes import letter, landscape, A4
from reportlab.lib.units import mm, inch

# Caminho para a imagem de fundo
logo = ImageReader('Certificado.png')

# Tamanho da página
size_page = (1235*mm, 873*mm)

# Tamanho Fonte Nome
size_name = 140

# Nome local
name_x = 0
name_y = 1380

# Fonte
font = "Helvetica-Bold"

def GeneratePDF(lista):
    try:
        for indice, nome in enumerate(lista):
            # Gerar certificado
            pdf = canvas.Canvas('{}.pdf'.format(nome))
            # Tamanho da página do certificado
            pdf.setPageSize(size_page)
            # Imagem de fundo
            pdf.drawImage(logo, 0, 0)
            pdf.setFont(font, size_name)
            pdf.drawString(name_x, name_y, '{}'.format(nome))
            pdf.save()
            print('{}.pdf criado com sucesso!'.format(nome))
    except:
        print('Erro ao gerar pdf')

lista = ["Gabriel Nunes Delfino", "Teste"]

GeneratePDF(lista)

1 answer

3


Centralizing text requires the drawing api to know where centralize your text - and it is you who has to do this account.

Many Apis have no function to automatically center text - in such cases, you have to account for "where the left corner of the text has to stay for the text to be centered" - (not a difficult account - it’s basically x = largura_da_linha / 2 - largura_do_texto / 2 ) .

If you were working with print in the terminal, and not with pdf, the method .format and f-strings can center a parameter on a given space - just place the string inside the keys :^ followed by the size of the white space. For example: "*{:^40}*".format("Stackoverflow") will leave 40 characters between the two asterisks and create a string with "stackoverflow" centered on that space:

'*             Stackoverflow              *'

In the case of reportlab, the canvas has the method drawCentredString (instead of the drawString ) that makes the central alignment for you - but you have to pass to it the "base point" - that is, in which coordinate "x" you want to be the center of the text - (the difference to the above method is that here you pass the direct center - do not need to compute the x coordinate of the left corner of the text)

To calculate the x of the "center" just take the page width and divide by two. Since you already have page_size, this is trivial - just change the line pdf.drawString(name_x, name_y, '{}'.format(nome)) for

pdf.drawCentredString(size_page[1] / 2, name_y, nome) 

(Note that "{}".format(nome) does nothing - format simply returns a new string, overriding occurrences of {} by the parameters you set as having nothing other than the {} is the same thing as using the direct name.)

Another thing that catches your attention there is that you are generating a PDF with an out-of-the-box size - the values you use in size_page are in millimeters - may be right if it’s a banner why you’re putting 1.2 meters x 80cm, but if it’s a certificate, you’ll want to use the A4 size which is 297 x 210mm.

As it is a vector format, the quality will always be the same - but if generate with the "giant size", if not pay attention to resize when printing, can go wrong.

  • My last vote of the day.

  • our. I’ve been at s.o. for about 8 years and I don’t think I’ve ever used all the votes. : -) . Win which medal?

  • 2

    You win this one: https://answall.com/help/badges/62/suffrage

  • 1

    I’m not lazy about voting on good content, I really vote.

  • 1

    the class needed to vote more - - is full of good answers around with "8 thousand views" and two votes.

  • If I put 297 x 210mm my background is very out, I could not other way but so. I tried what you went through, it did not work. https://github.com/nunesdelfino/Certified

  • Is there a better way to do that than I wish? I would recommend something?

  • have to resize the image before adding it to the canvas with the .drawImage -the documentation is not very good, and you will need to experiment- try to pass the parameters width and height when calling drawImage and see if it resizes the image.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.