Tkinter save user entered data in PDF file

User can enter data using one Text box and on button click a function is used to save the data in a PDF file.

Text data to PDF

Saving user entered data in a Tkinter application window through Text widget in a PDF file

Creating User interface to receive Data

Tkinter Text widget is used to enter multi-line data.
t1 = tk.Text(my_w,  height=12, width=45,bg='yellow')
One button is placed to call a function to read and save the user entered data.
b1=tk.Button(text='Generate PDF',command=lambda:gen_pdf())
Once the user clicks the button to save, the data entered inside the Text widget is collected and stored in a variable inside the function.
Line breaks are replaced to match the requirment in a PDF file.
text=text.replace('\n','<BR/>') # replace the line breaks
The text is used to create one Paragraph with associated style properties. Code for my_Style is given below.
p1 = Paragraph(text, my_Style)
After writing the data into a file, the user entered text is removed from the Text widget.
t1.delete('1.0',END) # Delete from position 0 till end
Full code is here.
import tkinter as tk
from tkinter import END
my_w = tk.Tk()
my_w.geometry("400x300")  # Size of the window 
my_w.title("")  # Adding a title
l1 = tk.Label(my_w,  text='Your Data', width=10 )  # added one Label 

t1 = tk.Text(my_w,  height=12, width=45,bg='yellow') # text box

b1=tk.Button(text='Generate PDF',command=lambda:gen_pdf())

### get PDF file libraries  
from reportlab.pdfgen import canvas
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import Paragraph
from reportlab.lib.pagesizes import  A4

# add Paragraph style ##
my_Style = ParagraphStyle('My Para style',
     backColor = '#F1F1F1',
     borderPadding = (20, 20, 20),
     leading = 20                           
width, height = A4 # size of the file 
# path and file name ##
my_path='G:\\My drive\\testing\\pypdf2\\my_pdf.pdf' 

def gen_pdf():
    text=t1.get("1.0",END) # collect user enterd data 
    text=text.replace('\n','<BR/>') # replace the line breaks
    p1 = Paragraph(text, my_Style) # add style 
    c = canvas.Canvas(my_path, pagesize=A4) # create canvas
    p1.wrapOn(c, 300, 50) # width , height of Paragraph 
    p1.drawOn(c, width-450,height-350) # location of Paragraph
    t1.delete('1.0',END)# Delete from position 0 till end 
    t1.update()     # Update text widget 
my_w.mainloop()  # Keep the window open
Tkinter Text widget PDF Shapes in PDF Projects using Tkinter
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2022 All rights reserved worldwide Privacy Policy Disclaimer