Problem with only one text item being added to PDF using PyMuPDF and Tkinter

76 views Asked by At

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()
1

There are 1 answers

1
acw1668 On BEST ANSWER

It is because the second and third rectangle areas are not tall enough to show the text.

Suggest to use page.insert_text() instead:

def add_text_to_pdf():
    ...

    # Define the text to be added
    text = text_entry.get()
    text2 = text_entry2.get()
    text3 = text_entry3.get()

    # Define the positions for the text (x, y)
    text_pos = fitz.Point(202, 626)
    text_pos2 = fitz.Point(104, 667)
    text_pos3 = fitz.Point(85, 711)

    # Add the text to the text positions
    page.insert_text(text_pos, text)
    page.insert_text(text_pos2, text2)
    page.insert_text(text_pos3, text3)

    ...