grok-3-mini-high· xAI
LMArena Human Preference 140K
Create a python script that allows me to import a prebuilt PDF form and add data points…
- User
Create a python script that allows me to import a prebuilt PDF form and add data points to it.
- Assistant
Below is a Python script that allows you to import a prebuilt PDF form and add data points to it. This script uses the
pypdflibrary, which is a popular and maintained library for working with PDFs. It supports filling out AcroForms (the standard PDF form type).Key Features:
- Input Handling: The script takes the path to the input PDF form, the output PDF path, and a list of field-value pairs as command-line arguments.
- Data Points: You provide data as key-value pairs (e.g.,
field1=value1), where the key is the name of the form field in the PDF, and the value is the data to fill in. - Error Handling: Basic error handling is included for common issues like missing fields or file not found.
- Requirements: You need to install the
pypdflibrary. Runpip install pypdfin your terminal before using this script.
How to Use:
-
Save the script to a file, e.g.,
fill_pdf_form.py. -
Run the script from the command line:
python fill_pdf_form.py input.pdf output.pdf field1=value1 field2=value2input.pdf: Path to your prebuilt PDF form.output.pdf: Path where the filled PDF will be saved.field1=value1: Replace with your form field names and values (e.g.,name=John Doefor a text field).
Example:
python fill_pdf_form.py form.pdf filled_form.pdf name=John Doe age=30 -
Notes on PDF Forms:
- This script works with AcroForms. Ensure your PDF has fillable fields (you can check this in Adobe Acrobat or similar tools).
- Field names must match exactly as they appear in the PDF (case-sensitive).
- For checkboxes, use values like
"Yes"or"Off"(depending on the PDF). For text fields, use strings.
Script Code:
import sys import os from pypdf import PdfReader, PdfWriter def fill_pdf_form(input_path, output_path, data): """ Fills a PDF form with the provided data. Args: - input_path (str): Path to the input PDF form. - output_path (str): Path to save the output PDF. - data (dict): A dictionary of form field names and their values. Returns: - None: Saves the filled PDF to output_path. """ if not os.path.exists(input_path): raise FileNotFoundError(f"Input file not found: {input_path}") reader = PdfReader(input_path) writer = PdfWriter() # Add all pages from the input PDF to the writer for page in reader.pages: writer.add_page(page) # Check if the PDF has a form if "/AcroForm" in reader.trailer.get("/Root", {}): try: # Update form fields; this works across pages for page_num in range(len(reader.pages)): writer.update_page_form_field_values(page_num, data) except KeyError as e: print(f"Error: Form field not found or invalid. Details: {e}") sys.exit(1) else: print("Warning: The input PDF does not appear to have a fillable form.") # Write the updated PDF to the output file with open(output_path, "wb") as output_file: writer.write(output_file) print(f"PDF form filled successfully and saved to {output_path}") if __name__ == "__main__": if len(sys.argv) < 4: print("Usage: python fill_pdf_form.py input.pdf output.pdf field1=value1 field2=value2 ...") print("Example: python fill_pdf_form.py form.pdf filled_form.pdf name=John Doe age=30") sys.exit(1) input_path = sys.argv[1] output_path = sys.argv[2] data = {} for arg in sys.argv[3:]: if "=" in arg: key, value = arg.split("=", 1) data[key] = value # Store as string; adjust if needed for specific field types else: print(f"Invalid argument: {arg}. Expected format: key=value") sys.exit(1) try: fill_pdf_form(input_path, output_path, data) except Exception as e: print(f"An error occurred: {e}") sys.exit(1)Explanation of the Code:
- Imports: We import necessary modules from
pypdfand standard libraries likesysandos. - Function
fill_pdf_form:- Reads the input PDF using
PdfReader. - Creates a new PDF with
PdfWriterand copies the pages. - Updates the form fields using
writer.update_page_form_field_values(). This method applies the data dictionary to the specified page (we loop through all pages to cover forms on any page). - Saves the updated PDF to the output path.
- Reads the input PDF using
- Main Block: Parses command-line arguments to get the input file, output file, and data dictionary. It then calls the function.
- Error Handling: Catches common errors like missing files or invalid fields.
Limitations and Tips:
- Field Types:
- Text fields: Use strings (e.g.,
"John Doe"). - Checkboxes: Use
"Yes"or"Off"(test with your PDF to confirm). - If you have more complex fields (e.g., dates or numbers), you might need to format the values appropriately.
- Text fields: Use strings (e.g.,
- Testing: Open the output PDF in a viewer like Adobe Acrobat to verify the fields are filled correctly.
- Advanced Usage: If your PDF has forms on specific pages or requires more customization, you can modify the script to target pages explicitly.
- Dependencies: Make sure to handle any library updates;
pypdfis actively maintained, so check for the latest version if you encounter issues.
If you run into any problems or need enhancements (e.g., reading data from a file instead of command-line args), let me know!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.