Skip to content
TheChatArchiveThe Chat Archive
grok-3-mini-high· xAIHugging Face LMArena Human Preference 140K

Create a python script that allows me to import a prebuilt PDF form and add data points…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with chatgpt-4o-latest-20250326’s answer.
  1. User

    Create a python script that allows me to import a prebuilt PDF form and add data points to it.

  2. 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 pypdf library, 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 pypdf library. Run pip install pypdf in your terminal before using this script.

    How to Use:

    1. Save the script to a file, e.g., fill_pdf_form.py.

    2. Run the script from the command line:

      python fill_pdf_form.py input.pdf output.pdf field1=value1 field2=value2
      
      • input.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 Doe for a text field).

      Example:

      python fill_pdf_form.py form.pdf filled_form.pdf name=John Doe age=30
      
    3. 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 pypdf and standard libraries like sys and os.
    • Function fill_pdf_form:
      • Reads the input PDF using PdfReader.
      • Creates a new PDF with PdfWriter and 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.
    • 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.
    • 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; pypdf is 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!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.