How to parse a document and prompt user input for placeholders in a React app

31 views Asked by At

I'm working on a project where I need to allow users to upload a document (e.g., .docx format) in a React app. After uploading, I want to parse the document to extract placeholders and then prompt the user to provide input for each placeholder. Finally, I'll replace the placeholders in the document with the user's input.

I'm looking for guidance on how to approach this task, especially in terms of:

Parsing the document to extract placeholders. Prompting the user for input corresponding to each placeholder. Dynamically updating the document with the user's input.

I currently have a proof-of-concept (POC) implemented in Python, where the backend handles document parsing and placeholder replacement to generate a document with the user's input. Here's the Python code:

# backend/app.py
from flask import Flask, request, jsonify
from flask_cors import CORS  
from docx import Document
import re

app = Flask(__name__)
CORS(app)


@app.route('/generate-doc', methods=['POST'])
def generate_doc():
    # Retrieve user input from request
    data = request.json

    # Load template, replace placeholders, and save generated document
    doc_path = "backend/template.docx"
    generate_doc_with_data(doc_path, data)

    return jsonify({'message': 'Document generated successfully'})

def get_placeholders(doc_path):
    """
    Extracts placeholders from the DOCX file using the python-docx library.
    """
    placeholders = set()
    doc = Document(doc_path)
    for paragraph in doc.paragraphs:
        for run in paragraph.runs:
            text = run.text
            for match in re.finditer(r"\[([^\]]+)\]", text):
                placeholders.add(match.group(1))
    return sorted(placeholders)

def generate_doc_with_data(doc_path, data):
    """
    Replaces placeholders in the DOCX file with user-provided values and saves the generated document.
    """
    doc = Document(doc_path)
    placeholders = get_placeholders(doc_path)

    for placeholder in placeholders:
        if placeholder in data:
            user_input = data[placeholder]
        else:
            user_input = input(f"Enter value for '{placeholder}': ")

        for paragraph in doc.paragraphs:
            for run in paragraph.runs:
                run.text = run.text.replace(f"[{placeholder}]", user_input)

    doc.save(f"{doc_path[:-5]}_generated.docx")

if __name__ == "__main__":
    app.run(debug=True)

While the Python solution works well in the console, I'm seeking advice on how to achieve similar functionality in my React app, be it with Node.js or any other way. Any suggestions or guidance on how to approach this task would be greatly appreciated!

0

There are 0 answers