I'm trying to make a gui using Tkinter where the user can type in text into three fields (name, date, occupation) and it will be added to three specified locations on a certain PDF. Right now, I'm having the issue where only the first item of text for name is being added to the PDF. I've tried changing up this code in all the ways that made sense to me to fix the problem and nothing has worked. I'd greatly appreciate any help.
Here's my code:
import fitz # PyMuPDF library
import tkinter as tk
from tkinter import filedialog
def add_text_to_pdf():
# Open the selected PDF document
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
pdf_document = fitz.open(file_path)
# For a single page PDF, you can set the page number to 1
page_number = 1
page = pdf_document.load_page(page_number - 1)
# Define the text to be added
text = text_entry.get()
text2 = text_entry.get()
text3 = text_entry.get()
# Define the rectangles for the text boxes (x1, y1, x2, y2)
text_rect = fitz.Rect(202, 626, 441, 647)
text_rect2 = fitz.Rect(104, 667, 359, 685)
text_rect3 = fitz.Rect(85, 711, 280, 726)
# Add the text to the text boxes
page.insert_textbox(text_rect, text)
page.insert_textbox(text_rect2, text2)
page.insert_textbox(text_rect3, text3)
# Save the modified PDF
output_file_path = filedialog.asksaveasfilename(defaultextension=".pdf", filetypes=[("PDF files", "*.pdf")])
pdf_document.save(output_file_path)
# Close the PDF document
pdf_document.close()
# Create a Tkinter window
window = tk.Tk()
window.title("PDF Text Editor")
tk.Label(window, text="Name").pack()
text_entry = tk.Entry(window)
text_entry.pack()
tk.Label(window, text="Date").pack()
text_entry2 = tk.Entry(window)
text_entry2.pack()
tk.Label(window, text="Occupation").pack()
text_entry3 = tk.Entry(window)
text_entry3.pack()
# Create a button to trigger the PDF editing process
add_text_button = tk.Button(window, text="Add Text to PDF", command=add_text_to_pdf)
add_text_button.pack()
# Start the Tkinter main loop
window.mainloop()
It is because the second and third rectangle areas are not tall enough to show the text.
Suggest to use
page.insert_text()
instead: