How to create a PDF from Dictionary data extracted from a . txt (Python) file

Asked

Viewed 1,795 times

1

I have a dict() with string data extracted from a arquivo.txt.

dic = {}
dic[valor[0]] = valor[1]
print(dic)
>>> dic = {'Almir': 44, 'Ana': 36 ....}

I would like to save organized in PDF as follows:

nome : 8585
nome : 83838

2 answers

3

  • Dude, it worked, but when I try to put with more than one line the data is saved all in one line

  • could help me?

  • Is it really necessary to use PDF? It’s not a practical format to manipulate via code.

1


As suggested by @cryptotux, use the library reportlab.

To generate the PDF through a dictionary, where each word will be on a line, do:

import os
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch

# Aqui vem o código de criação do dicionário `dic`

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

# Move a origem do cursor para a parte superior esquerda
c.translate(inch,inch)

# Inicia um objeto texto limitando a área para que linhas 
# muito grandes, não ultrapassem a margem.
textobject = c.beginText(0, 650)
textobject.setFont("Helvetica-Oblique", 14)

# Percorrendo o dicionário definido anteriormente
for key, value in dic.items():
    textobject.textLine(key + ' : ' + value)

c.drawText(textobject)

c.showPage()
c.save()

os.system('arquivo.pdf')

Browser other questions tagged

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