fillpdf

repository·main·Indexed 41 days ago

https://github.com/t-houssian/fillpdf

A lightweight Python library for PDF manipulation, focusing on filling form fields, flattening PDFs, and programmatically inserting text, images, and interactive elements like dropdowns and radio buttons. It includes functions such as write_fillable_pdf, flatten_pdf, and get_form_fields, as well as CLI tools extractfillpdf and insertfillpdf for JSON-based field extraction and insertion.

Tokens
3.7K
Snippets
20
Records
20
Agent score
98%

What's inside fillpdf

  1. Install fillpdf via pip or conda

    main

    To use fillpdf, install the package via pip. If you plan to use the as_images=True mode of the flattenpdf function, you must also install poppler via conda.

    pip install fillpdf
    conda install -c conda-forge poppler
    pip install fillpdf
    conda install -c conda-forge poppler
  2. Flatten a PDF to make fields uneditable

    main

    When calling write_fillable_pdf, setting the flatten parameter to True makes the form fields uneditable by setting the /Ff (Field Flags) bit. This effectively 'burns' the text into the document so users cannot change the values.

    # This will create a PDF where the fields are no longer interactive
    fillpdfs.write_fillable_pdf('ex2.pdf', 'flattened.pdf', data_dict, flatten=True)
  3. List and inspect PDF form fields

    main

    Use get_form_fields to retrieve a dictionary of all form field names and their current values, or print_form_fields to print them directly to the console. This is the first step in automating PDF filling to identify the exact keys needed for your data_dict.

    Parameters:

    • input_pdf_path: Path to the source PDF.
    • sort (bool): If True, sorts the dictionary alphabetically. Defaults to False.
    • page_number (int): If provided, retrieves values only from the specified page number.
    from fillpdf import fillpdfs
    
    # Get a dictionary of fields
    data_dict = fillpdfs.get_form_fields('blank.pdf')
    
    # Or print them directly
    fillpdfs.print_form_fields('blank.pdf')
  4. Get coordinate maps for element placement

    main

    To accurately place elements using place_* functions, you can use get_coordinate_map to generate a template or map of the PDF. This helps in identifying the correct x and y coordinates for your desired locations.

    from fillpdf import fillpdfs
    
    fillpdfs.get_coordinate_map('template.pdf', 'template-2.pdf', page_number=1)
  5. Flatten a PDF to make it non-editable

    main

    Use flatten_pdf to convert a fillable PDF into a static, non-editable version.

    Parameters:

    • input_pdf_path: Path to the fillable PDF.
    • output_pdf_path: Path for the flattened output.
    • as_images (bool): If False (default), it updates individual annotations. If True, it converts the PDF to images and reinserts them. Use as_images=True if the standard flattening method fails. Note: This method requires poppler to be installed on your system.
    from fillpdf import fillpdfs
    
    # Standard flattening
    fillpdfs.flatten_pdf('new.pdf', 'newflat.pdf')
    
    # Flattening via image conversion (requires poppler)
    fillpdfs.flatten_pdf('new.pdf', 'newflat.pdf', as_images=True)
  6. Fill a PDF with data

    main

    The write_fillable_pdf function allows you to populate an existing PDF form using a dictionary where keys are field names and values are the content to be inserted.

    Data Mapping Rules:

    • Checkboxes & Radio Buttons: Use 'Yes' to fill/select and 'Off' to leave empty.
    • Drop-downs: Provide the exact string name of the desired option.
    • Radio Groups: Use index strings: '0' for the first option, '1' for the second, etc.

    Parameters:

    • input_pdf_path: Path to the source PDF.
    • output_pdf_path: Path where the filled PDF will be saved.
    • data_dict: Dictionary mapping field names to values.
    • flatten (bool): If True, the resulting PDF will be non-editable. Defaults to False.
    from fillpdf import fillpdfs
    
    data_dict = {
        'Address1 Text Box': '500 West Main Street',
        'Driving License Check Box': 'Yes',
        'Language 1 Check Box': 'Off',
        'RadioGroup': '0' # Selects the first option
    }
    
    fillpdfs.write_fillable_pdf('blank.pdf', 'new.pdf', data_dict)
  7. Insert new elements (Text, Images, Dropdowns) into a PDF

    main

    The place_* functions allow you to programmatically add new elements to a PDF at specific coordinates. Most of these functions require an input_pdf_path, an output_map_path (the new file generated), and a page_number.

    Available Placement Functions:

    • place_text(text, x, y, input_pdf_path, output_map_path, page_number, font_size=12, font_name="helv", color=None): Adds raw text.
    • place_text_box(field_name, prefilled_text, x, y, ...): Adds a text input field.
    • place_image(file_name, x, y, input_pdf_path, output_map_path, page_number, width=10, height=10): Places an image file.
    • place_dropdown(field_name, values, x, y, ...): Adds a dropdown menu with specific options.
    • place_radiobutton(field_name, x, y, ...): Adds a radio button.

    Coordinate System: x is the top-left corner horizontal coordinate; y is the top-right corner vertical coordinate.

    from fillpdf import fillpdfs
    
    # Place text
    fillpdfs.place_text('Yo', 50, 50, 'template.pdf', 'out.pdf', 1)
    
    # Place an image
    fillpdfs.place_image('mush.png', 50, 50, 'template.pdf', 'out.pdf', 1, width=200, height=200)
    
    # Place a dropdown
    fillpdfs.place_dropdown('dropField-1', ('Berlin', 'Munich'), 0, 0, 'sample.pdf', 'out.pdf', 1, width=100, height=20)
  8. Reference: Supported fonts for placement functions

    main

    When using place_text, place_text_box, place_dropdown, or place_radiobutton, you can specify a font_name. Use the following keys to map to standard PDF fonts:

    # Mapping of keys to PDF fonts
    {
        'courier': 'Courier',
        'courier-bold': 'Courier-Bold',
        'helvetica': 'Helvetica',
        'helv': 'Helvetica',
        'hebo': 'Helvetica-Bold',
        'times-roman': 'Times-Roman',
        'times-bold': 'Times-Bold',
        'symbol': 'Symbol',
        'symb': 'Symbol',
        'zapfdingbats': 'ZapfDingbats',
        'zadb': 'ZapfDingbats',
        # ... and other variations like 'heit' (Helvetica-Oblique), 'tibo' (Times-BoldItalic), etc.
    }
  9. Insert data into PDF using insertfillpdf CLI

    main

    The insertfillpdf command takes a modified JSON file and applies its contents to a PDF, producing a new PDF file.

    Usage: insertfillpdf -j <input_json_path> -o <output_pdf_path> <input_pdf_path>

    Arguments:

    • input_pdf_path: The source PDF file.
    • -j, --JSON <input_json_path>: The JSON file containing the field data (generated via extractfillpdf). If not provided, it defaults to the input filename with a .json extension.
    • -o, --output <output_pdf_path>: The path where the new PDF will be written. If not provided, it defaults to the input filename with an _out.pdf extension.
    • -v, --verbose: Set loglevel to INFO.
    • -vv, --very-verbose: Set loglevel to DEBUG.
    • --version: Show program version and exit.
    insertfillpdf -j blank.json -o new.pdf blank.pdf
  10. Extract PDF fields using extractfillpdf CLI

    main

    The extractfillpdf command extracts the fields and contents of a PDF into a JSON file.

    Usage:

    • extractfillpdf <input_pdf_path>: Extracts fields to a JSON file with the same name as the input but a .json extension.
    • extractfillpdf <input_pdf_path> -o <output_json_path>: Specifies a custom path for the resulting JSON file.

    Arguments:

    • input_pdf_path: Path to the PDF you want to alter.
    • -o, --output: Output file to write the result. If not provided, it defaults to the input filename with a .json extension.
    • -v, --verbose: Set loglevel to INFO.
    • -vv, --very-verbose: Set loglevel to DEBUG.
    • --version: Show program version and exit.
    extractfillpdf blank.pdf
    # or
    extractfillpdf blank.pdf -o data.json
  11. Pretty print form fields with print_form_fields()

    main

    Use print_form_fields(input_pdf_path) to retrieve the form fields and print them to the console in a readable dictionary format. This is useful for inspecting the available keys in a PDF template.

    from fillpdf import fillpdfs
    
    fillpdfs.print_form_fields('ex2.pdf')