Uncategorized

Having trouble with HTML to Flask to Python pdfrw script, pdf is not filling holding values, and flask is not writing to the fields_data


I’m having trouble with creating a PDF form filler from an HTML page, basically I want to convert radio box selections to text that will fill in a PDF (ie selecting specific facility will fill in the facility field).
My HTML is:

<!DOCTYPE html>
<html>
<head>
    <title>PDF Form Autopopulation</title>
    <script>
        function generateFieldsData() {
            var fieldsData = {};


            var facility = document.getElementById('facility').value;
            fieldsData['Facility'] = facility;

            // Update the hidden input with the JSON representation of fields_data
            document.getElementById('fields_data').value = JSON.stringify(fieldsData);
        }
    </script>
</head>
<body>
    <h1>PDF Form Autopopulation</h1>
    <form action="/process_form" method="post" onsubmit="generateFieldsData()">

        <label for="facility">Facility:</label><br>
        <select id="facility" name="facility">
            <option value="Facility1">Faculity1</option>
            <option value="Facility2"> Faculity3</option>
            <option value="Facility3"> Faculity3</option>
            <!-- Add more options as needed -->
        </select><br><br>

        <!-- Hidden input to store fields_data -->
        <input type="hidden" id="fields_data" name="fields_data">

        <input type="submit" value="Generate PDF">
    </form>

</body>
</html>

The flask server script is:

`from flask import Flask, render_template, request, send_file
import json
from my_package.form_Fill.fill_pdf import fill_pdf  # Adjust import based on your file structure

app = Flask(__name__)

@app.route("https://stackoverflow.com/")
def index():
    return render_template('Finalforms.html')

@app.route('/process_form', methods=['POST'])
def process_form():
    if request.method == 'POST':
        # Initialize fields_data dictionary
        fields_data = {}

       
        facility = request.form.get('facility')
        if facility:
            fields_data['Facility_0'] = facility



        # Call the function to fill PDF using the form data
        # Adjust these paths according to your setup
        input_pdf_path="/Users/ pythonProject/static/PDFs/AdultSideConsent.pdf"
        output_pdf_path="/Users/pythonProject/static/PDFs/new.pdf"

        try:
            # Call your fill_pdf function with the appropriate arguments
            fill_pdf(input_pdf_path, output_pdf_path, fields_data)

            # Return the generated PDF file as a response
            return send_file(output_pdf_path, as_attachment=True)
        except Exception as e:
            return f"Error generating PDF: {str(e)}"


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

And the python package script is:

from pdfrw import PdfReader, PdfWriter, PdfDict, IndirectPdfDict, PdfName, PdfObject
 
def fill_pdf(input_pdf, output_pdf, fields_data):

    template_pdf = PdfReader(output_pdf)
    writer = PdfWriter()
input_pdf_path.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject("true")))


    for page_num in range(len(template_pdf.pages)):
        page = template_pdf.pages[page_num]
        annotations = page.get('/Annots')
        if annotations:
            for annotation in annotations:
                if annotation['/Subtype'] == '/Widget':
                    field_name = annotation.get('/T')
                    if field_name in fields_data:
                        annotation.update(PdfDict(V='{}'.format(fields_data[field_name])))

        writer.addpage(page)

    writer.write(output_pdf)

# Example usage:
input_pdf_path="/users/pythonProject/static/PDFs/Facility.pdf"  # Replace with your input PDF path
output_pdf_path="/Users/pythonProject/static/PDFs/new.pdf"  # Replace with your output PDF path

fields_data = {

    'Facility_1': 'Facility_0',  # Facility
    
}


print(fields_data)
fill_pdf(input_pdf_path, output_pdf_path, fields_data)

I get fields_data variables in the flask script, however I’m just returning the placeholder values on the fields_data when I print and those additionally are not getting pushed to the PDF. I have already recreated the PDF to ensure no security settings and have attempted conversion to a PDF/a. There also is no data opening it in acrobat DC, preview, or in the browser.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *