1

I am making a calendar app using Tkinter in Python3 and I have a problem with the .txt to .pdf conversion.

My code saves user tasks to a .txt file and then can convert this .txt file to a pdf with the press of a button.

If the user creates a pdf with the tasks contained in the .txt file, then changes the .txt file and converts it to a pdf again, it will always convert the contents of the previous saved .txt file.
The only solution is to restart the whole program but I don't want that.

What can I change in my code so every time I change the .txt contents the pdf file contains the upgraded .txt file contents?

I will share the create pdf function below.

#function to create pdf
def PDFCreate():
    pdf.set_font("Impact", size=15)
    with open("FoundTasks.txt", "r", encoding = 'utf-8') as PDFTasks:
        content = PDFTasks.read()
        pdf.multi_cell(0, 10, txt=content, align='C')

    # create or overwrite the tasks.pdf file with the contents of FoundTasks.txt
    pdf.output("Tasks.pdf")
QHarr
  • 83,427
  • 12
  • 54
  • 101

1 Answers1

0

Instantiate the class FPDF inside the PDFCreate() function

I think you have only to instantiate the pdf object inside your function PDFCreate() as you can see in the code below.

File pdf_create.py:

from fpdf import FPDF

#function to create pdf
def PDFCreate():
    pdf = FPDF()       # <--------------------------- add this instruction
    pdf.add_page()     # <--------------------------- add this instruction

    # the rest of the code is correct
    pdf.set_font("Impact", size=15)
    with open("FoundTasks.txt", "r", encoding = 'utf-8') as PDFTasks:
        content = PDFTasks.read()
        pdf.multi_cell(0, 10, txt=content, align='C')

    # create or overwrite the tasks.pdf file with the contents of FoundTasks.txt
    pdf.output("Tasks.pdf")

How to test the previous function

To test your code (with my modification) I have used the following script (saved in the file from_txt_to_pdf.py in the same folder of pdf_create.py).

import webbrowser
from pdf_create import PDFCreate

def main():
    choice = 'y'
    while (choice == 'y'):
        choice = input("Create the PDF file Tasks.pdf (y/n)?")
        if choice == 'y':
            PDFCreate()
            webbrowser.open_new('Tasks.pdf')

main()

I have successfully test the previous code in my system:

Every time I change the content of the file FoundTasks.txt and choice y when the input() function prompt me the choice message Create the PDF file Tasks.pdf (y/n)?, the pdf file FoundTasks changes.

IN your context instead of selecting y you will have to click to your button!!

frankfalse
  • 1,553
  • 1
  • 4
  • 17