How to create a PDF from a list

Asked

Viewed 130 times

0

want to create a PDF from a list but this resulting the following error:

C:\Users\nicperei\Desktop\pyCodes>py web.py
Traceback (most recent call last):
  File "web.py", line 22, in <module>
    pdf.drawString(100, 10, listaFinal)
  File "C:\Users\nicperei\AppData\Roaming\Python\Python36\site-packages\reportlab\pdfgen\canvas.py", line 1560, in drawString
    text = text.decode('utf-8')
AttributeError: 'list' object has no attribute 'decode'

C:\Users\nicperei\Desktop\pyCodes>

follows my code:

import requests
from bs4 import BeautifulSoup
from reportlab.pdfgen import canvas

url ='http://servicos2.sjc.sp.gov.br/servicos/horario-e-itinerario.aspx?acao=p&opcao=1&txt='

r = requests.get(url)
listaFinal = []
soup = BeautifulSoup(r.text, 'lxml')
lista_intinerarios = soup.find_all('table', class_='textosm')
urlsjc = 'http://www.sjc.sp.gov.br'
for lista_td in lista_intinerarios:
    lista = lista_td.find_all('td')
    for lista_dados in lista:
        if lista_dados.next_element.name == 'a':
            url_it = '{0}{1}'.format(urlsjc,lista_dados.next_element.get('href'))
            listaFinal.append(url_it)
        else:
            listaFinal.append(lista_dados.next_element)

pdf = canvas.Canvas("Site_Prefeitura3.pdf")
pdf.drawString(100, 200,listaFinal)
pdf.save()

print(listaFinal)
print("Executado com sucesso...")

Thanks in advance!

  • Error says the function pdf.drawText takes only 2 arguments, but you passed 4.

  • I’ve changed from pdf.drawText for pdf.drawString

1 answer

1


So you have to iterate your list, see this simple example

from reportlab.pdfgen import canvas

listaFinal = ['oi', 'eu', 'sou', 'goku']

pdf = canvas.Canvas("Site_Prefeitura3.pdf")
for cont, l in enumerate(listaFinal):
    # Lembre de mudar a posição para não sobrepor uma string com outra da lista
    pdf.drawString(100, 300-15*cont,l)
pdf.save()

If the file needs to have more than one page you can use the function pdf.showPage(). See this example below:

from reportlab.pdfgen import canvas
pdf = canvas.Canvas('paginas.pdf')

pdf.drawString(100, 100, "Primeira página")
pdf.showPage()

pdf.drawString(200, 100, "Segunda página")
pdf.showPage()

pdf.drawString(300, 100, "Terceira página")
pdf.showPage()

pdf.save()
  • Thanks, it worked!

  • it does not print all the data and only creates a PDF sheet, as it could to do to put all the data and generate more pages?

  • Hello Nicolas, see in the edition, a simple example of how you can create the pdf with more than one page.

  • Thank you!!

Browser other questions tagged

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