user10295588
user10295588

Reputation:

How can I add text from a txt file to a pdf python file

The python code below scans a txt file and adds the values ​​in a python array to then generate a pdf file. How can I read the txt file below and add the values ​​to the given array?

Python Code:

 from fpdf import FPDF

def createtable(spacing=1):
    #data = [['Articolo / Risorsa', 'Descrizione', 'Quantita'],
    #        ['Mike', 'Driscoll', '3'],
    #        ['John', 'Doe', '2'],
    #        ['Nina', 'Ma', '2']
    #        ]
    file=open("temp.txt","r")
    data = [['Articolo / Risorsa', 'Descrizione', 'Quantita']]
    pdf = FPDF()
    pdf.set_font("Arial", size=12)
    pdf.add_page()
    pdf.image("logo.jpg", x=50, y=8, w=100)
    pdf.ln(30)
    #pdf.cell(200, 10, txt="Welcome to Python! \n \n \r ", ln=1, align="C")
    col_width = pdf.w / 4.5
    row_height = pdf.font_size

    for row in data:
        for item in row:
            pdf.cell(col_width, row_height*spacing,txt=item, border=1)
        pdf.ln(row_height*spacing)

    pdf.output('rapportino.pdf')

if __name__ == '__main__':
    createtable()
    print("\n \n Rapportini in stampa \n \n ")

File txt:

gw44;prova deec;2
gw21;ksdkoksdok;78
kosd;ldsldpsdp;21

Upvotes: 0

Views: 819

Answers (1)

Abdeslem SMAHI
Abdeslem SMAHI

Reputation: 453

you can use this code to read the file and fill data

with open("file.txt", "r") as f:
    lines = f.readlines()
    data = [line.split("\n")[0].split(";") for line in lines]

Upvotes: 1

Related Questions