Generate and save PDFs with Student Information from user input using Python and SQLite
Create a Python GUI to Save Student Data as PDF Using Tkinter, SQLite, and ReportLab
Part 1 : User selection of Path to save PDF file
By using tkitner filedialog.asksaveasfile we will create a dialog for user to browse and save file in local system.
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import asksaveasfile
from reportlab.pdfgen import canvas
my_w = tk.Tk()
my_w.geometry("400x300") # Size of the window
my_w.title('www.plus2net.com')
my_font1=('times', 18, 'bold')
l1 = tk.Label(my_w,text='Save File',width=30,font=my_font1)
l1.grid(row=1,column=1)
b1 = tk.Button(my_w, text='Save',
width=20,command = lambda:save_file())
b1.grid(row=2,column=1)
def save_file():
file = filedialog.asksaveasfilename(
filetypes=[("pdf file", ".pdf")],
defaultextension=".pdf")
save_pdf(file) # create and save the pdf in given path
def save_pdf(my_path): # save the pdf file in given path
c = canvas.Canvas(my_path,bottomup=0)
c.drawString(200,200,"Hello World") # write text in page
c.showPage() # saves current page
c.save() # stores the file and close the canvas
my_w.destroy() #Close the window
my_w.mainloop() # Keep the window open
Importing Libraries: The script imports `tkinter` for the GUI, `filedialog` for the save dialog, and `canvas` from `reportlab` to generate PDFs.
GUI Setup: The window (`my_w`) contains a label and a "Save" button. The button calls the `save_file()` function when clicked.
save_file() Function: Opens a save dialog, where the user can choose the filename and location. It then calls `save_pdf()` to create the PDF.
save_pdf() Function: Uses `canvas` to generate a PDF file with the "Hello World" text and saves it to the specified location. The window then closes.
Part II : Taking user input to PDF document
In this updated code, an input field (Entry widget) is added to the GUI to collect a student ID from the user.
Entry Widget:
e1 = tk.Entry(my_w, width=3, bg='lightyellow')
This widget allows the user to input the student ID directly into the GUI.
Using Input in PDF Generation:
c.drawString(200, 200, "Hello World " + e1.get())
The entered student ID is retrieved using e1.get() and is combined with the text "Hello World". This text is then printed on the PDF at the specified coordinates.
This demonstrates how user input can be dynamically incorporated into the content of a generated PDF file.
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import asksaveasfile
from reportlab.pdfgen import canvas
my_w = tk.Tk()
my_w.geometry("400x300") # Size of the window
my_w.title('www.plus2net.com')
my_font1=('times', 18, 'bold')
l1 = tk.Label(my_w,text='Save File',width=30,font=my_font1)
l1.grid(row=1,column=1,columnspan=2)
e1=tk.Entry(my_w,width=3,bg='lightyellow')
e1.grid(row=2,column=1)
b1 = tk.Button(my_w, text='Save',
width=20,command = lambda:save_file())
b1.grid(row=2,column=2)
def save_file():
file = filedialog.asksaveasfilename(
filetypes=[("pdf file", ".pdf")],
defaultextension=".pdf")
save_pdf(file)
def save_pdf(my_path):
c = canvas.Canvas(my_path,bottomup=0)
c.drawString(200,200,"Hello World " + e1.get()) # write text in page
c.showPage() # saves current page
c.save() # stores the file and close the canvas
my_w.destroy() #Close the window
my_w.mainloop() # Keep the window open
Part III: Using user input to collect data from database and use the same for pdf generation
This code creates a GUI application that takes a student ID as input, retrieves the corresponding student details from a SQLite database, and saves the information to a PDF file.
User Input: The user enters a student ID into a `tk.Entry` widget (`e1`). This ID is used to query the database for the student's details.
Retrieving Data: The `save_pdf()` function queries the database for the student details using the provided ID. The result is stored in `data_row`.
Generating PDF: The `reportlab` library's `canvas` is used to create a PDF. The student's name and class are written to the PDF at specified positions.
Saving the File: The PDF is saved to the path specified by the user in the save dialog, and the application window closes after saving.
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import asksaveasfile
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from sqlalchemy import create_engine,text
my_conn = create_engine("sqlite:///E:\\testing\\sqlite\\my_db.db")
my_conn=my_conn.connect()
my_w = tk.Tk()
my_w.geometry("400x300") # Size of the window
my_w.title('www.plus2net.com')
my_font1=('times', 18, 'bold')
l1 = tk.Label(my_w,text='Save File',width=30,font=my_font1)
l1.grid(row=1,column=1,columnspan=2)
e1=tk.Entry(my_w,width=6,bg='lightyellow',font=16)
e1.grid(row=2,column=1)
b1 = tk.Button(my_w, text='Save',
width=20,command = lambda:save_file())
b1.grid(row=2,column=2)
def save_file():
file = filedialog.asksaveasfilename(
filetypes=[("pdf file", ".pdf")],
defaultextension=".pdf")
save_pdf(file)
def save_pdf(my_path):
c = canvas.Canvas(my_path,bottomup=0)
r_set=my_conn.execute(text("SELECT * from student where id= "+ e1.get()))
data_row=r_set.fetchone()
#print(data_row[1])
c.drawRightString(2*inch,2*inch,'Name:')
c.drawRightString(4*inch,2*inch,data_row[1])
c.drawRightString(2*inch,2.3*inch,'Class:')
c.drawRightString(4*inch,2.3*inch,data_row[2])
c.showPage() # saves current page
c.save() # stores the file and close the canvas
my_w.destroy() #Close the window
my_w.mainloop() # Keep the window open
Here, we're demonstrating how to extract two columns from the student table and write them into a PDF file. This approach can be extended to include additional columns by joining multiple tables to retrieve comprehensive details. The same method can be adapted to create detailed applications or student forms for saving or printing, making it a versatile solution for various data-driven tasks.