import pandas as pd from docx import Document from docx.shared import Pt from…
- User
import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st
Paths to the Word templates
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows
def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path)
# Determine if using "Yes" or "No" template for identifier text if "Confidential" in template_path: # For the Yes template identifier_text = f"Confidential Matter {matter_count}" else: # For the No template identifier_text = f"Publishable Matter {matter_count}" existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0] # Replace or append the numeric identifier if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) # Update the number doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found cell = doc.tables[0].cell(1, 0) # Apply the specified formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the rest of the document with the provided data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" doc.save(output_path) print(f"Saved individual document: {output_path}")def combine_documents(document_paths, output_path): """Combine multiple documents into a single document.""" combined_doc = Document()
for doc_path in document_paths: sub_doc = Document(doc_path) for element in sub_doc.element.body: combined_doc.element.body.append(element) combined_doc.save(output_path) print(f"Combined document saved: {output_path}")def populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs_no = [] individual_docs_yes = []
# Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs_no.append(temporary_output_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs_yes.append(temporary_output_path) # Combine all individual documents into one combine_documents(individual_docs_no + individual_docs_yes, output_path) # Clean up temporary documents for doc_path in individual_docs_no + individual_docs_yes: os.remove(doc_path) print("Temporary documents cleaned up.") except Exception as e: print(f"Unexpected error: {e}")Streamlit application
def main(): st.title("Fill Chambers and Partners Form")
# User uploads excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.docx" populate_chambers(excel_file, output_path) st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) else: st.error("Please upload the Excel file.")if name == "main": main() in this before publishable pdf means Tempalte_path_NO and after that before tempalte_pathyes i want to add some pages which i will append in two pdfs one is before.pdf and other is after.pdf
- Assistant
To add pages from two PDF documents (
before.pdfandafter.pdf) into the generated documents for both "No" (publishable) and "Yes" (confidential) cases, you can use thePyPDF2library (orpikepdffor more advanced operations). Below are the steps and modifications required to integrate this new functionality into your existing code.Step 1: Install the Required Packages
If you haven't already installed
PyPDF2, you can do so using pip:pip install PyPDF2Step 2: Update the Code to Include PDF Pages
You would need to modify the
create_individual_documentfunction to append thebefore.pdfpages to the beginning of the document and theafter.pdfpages at the end before saving it. Here's how to do it:- Open the existing Word document.
- Convert the Word document to a PDF.
- Merge it with
before.pdfandafter.pdf.
Here is the modified code that integrates the above steps:
import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st from PyPDF2 import PdfReader, PdfWriter from docx2pdf import convert # Ensure to install docx2pdf if you want to convert DOCX to PDF # Paths to the Word templates and PDFs TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows BEFORE_PDF_PATH = r"C:\path\to\your\before.pdf" AFTER_PDF_PATH = r"C:\path\to\your\after.pdf" # Function to append PDFs def append_pdfs(pdf_list, output_pdf): writer = PdfWriter() for pdf in pdf_list: reader = PdfReader(pdf) for page in range(len(reader.pages)): writer.add_page(reader.pages[page]) with open(output_pdf, 'wb') as f: writer.write(f) def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path) # Identifying text based on template type if "Confidential" in template_path: identifier_text = f"Confidential Matter {matter_count}" else: identifier_text = f"Publishable Matter {matter_count}" # Update the table cell with matter count existing_text = doc.tables[0].cell(1, 0).text if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" # Save the document temporarily and convert it to PDF temp_docx_path = output_path doc.save(temp_docx_path) temp_pdf_path = temp_docx_path.replace('.docx', '.pdf') convert(temp_docx_path) # Convert to PDF os.rename(temp_docx_path.replace('.docx', '.pdf'), temp_pdf_path) # Append PDFs combined_pdf_path = temp_pdf_path.replace('.pdf', '_combined.pdf') append_pdfs([BEFORE_PDF_PATH, temp_pdf_path, AFTER_PDF_PATH], combined_pdf_path) # Clean up os.remove(temp_pdf_path) # Remove temp PDF after combining print(f"Saved combined document: {combined_pdf_path}") return combined_pdf_path def combine_documents(document_paths, output_pdf_path): """Combine multiple PDF documents into a single PDF document.""" append_pdfs(document_paths, output_pdf_path) def populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs = [] # Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Combine all individual documents into one combine_documents(individual_docs, output_path) # Clean up temporary documents for doc_path in individual_docs: os.remove(doc_path) print("Temporary documents cleaned up.") except Exception as e: print(f"Unexpected error: {e}") # Streamlit application def main(): st.title("Fill Chambers and Partners Form") excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.pdf" populate_chambers(excel_file, output_path) st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.pdf", mime="application/pdf" ) else: st.error("Please upload the Excel file.") if __name__ == "__main__": main()Key Changes Made:
- PDF Handling: The
create_individual_documentfunction now creates a temporary PDF of the Word document and appends the specified PDF pages before and after the document. - Merge Function: The
append_pdfsfunction is added to combine multiple PDF files. - Update to Streamlit: The
output_pathis saved as a PDF and uploaded to Streamlit for download.
Note:
Make sure the paths to your PDF files (
BEFORE_PDF_PATHandAFTER_PDF_PATH) and the required libraries are correctly set up. This code assumes that you are merging PDF files, so ensure you have the necessary permissions and that your file paths are correct. - User
Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\scriptrunner\exec_code.py", line 88, in exec_func_with_error_handling result = func() ^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 590, in code_to_exec exec(code, module.dict) File "C:\Users\Administrator\Desktop\Bd team\fulltemplate.py", line 146, in main() File "C:\Users\Administrator\Desktop\Bd team\fulltemplate.py", line 135, in main with open(output_path, "rb") as f: ^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: 'combined_confidential_publishable.pdf'
- Assistant
The
FileNotFoundErroryou're encountering indicates that the specified file (combined_confidential_publishable.pdf) does not exist when you try to open it for download in your Streamlit application.This issue can occur for a few reasons:
- The PDF was not generated successfully. There might be an error in the PDF generation logic that prevents the file from being created.
- The file path could be incorrect. If the directory structure is not valid or if the permissions prevent creating a file in that location, it won't be created.
- Temporary files cleanup. If your cleanup process removes files before you attempt to use them.
Step-by-Step Debugging and Fixes
-
Check for Errors in PDF Generation: Print or log intermediary steps to see if the PDF generation process is functioning correctly. You can add print statements or logging to confirm that the method
populate_chamberscompletes without errors. -
Check the Output Path:
- Ensure that
output_pathis being set correctly. - Adjust the path if necessary to include a full directory structure where you have write permissions.
- For example, instead of just the file name, try providing a full path like so:
output_path = r"C:\path\to\your\output\combined_confidential_publishable.pdf"
- Ensure that
-
Avoiding Cleanup Errors: After generating the PDF, avoid deleting the file before it's downloaded. You can wrap the cleanup in a
try/finallyor similar construct to ensure it only runs after the file has been successfully handled by Streamlit.
Code Modifications
Here’s a modified version of the
populate_chambersfunction to handle the PDF generation checking more robustly:def populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs = [] # Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Ensure that individual_docs are generated successfully if not individual_docs: raise Exception("No PDF files were generated.") # Combine all individual documents into one combine_documents(individual_docs, output_path) print(f"Combined document has been saved to: {output_path}") except Exception as e: print(f"Unexpected error: {e}")Additional Debugging
Within your
create_individual_documentfunction, make sure to print confirmation messages or errors to the console to track progress and catch any problems:def create_individual_document(template_path, data, matter_count, output_path): try: # Your existing code... # Check if temp PDF is created if not os.path.exists(temp_pdf_path): print(f"Failed to create temp PDF at {temp_pdf_path}") return None # Append PDFs combined_pdf_path = temp_pdf_path.replace('.pdf', '_combined.pdf') append_pdfs([BEFORE_PDF_PATH, temp_pdf_path, AFTER_PDF_PATH], combined_pdf_path) return combined_pdf_path # Return the path of the combined PDF except Exception as e: print(f"Error creating individual document: {e}") return NoneTesting
To verify if the problem is resolved:
- Run your application and carefully monitor the console output for any error messages during the PDF generation process.
- Check for successful creation of all expected temporary files in your working directory.
- Finally, ensure that the cleanup does not delete necessary files before they are downloaded.
With these adjustments, you should be able to identify where the issue lies and ensure the PDF file is created and available for download as expected.
- User
provide this full upadted code import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st from PyPDF2 import PdfReader, PdfWriter from docx2pdf import convert # Ensure to install docx2pdf if you want to convert DOCX to PDF
Paths to the Word templates and PDFs
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows BEFORE_PDF_PATH = r"C:\Administrator\Desktop\new\before.pdf" AFTER_PDF_PATH = r"C:\Administrator\Desktop\new\After.pdf"
Function to append PDFs
def append_pdfs(pdf_list, output_pdf): writer = PdfWriter()
for pdf in pdf_list: reader = PdfReader(pdf) for page in range(len(reader.pages)): writer.add_page(reader.pages[page]) with open(output_pdf, 'wb') as f: writer.write(f)def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path)
# Identifying text based on template type if "Confidential" in template_path: identifier_text = f"Confidential Matter {matter_count}" else: identifier_text = f"Publishable Matter {matter_count}" # Update the table cell with matter count existing_text = doc.tables[0].cell(1, 0).text if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" # Save the document temporarily and convert it to PDF temp_docx_path = output_path doc.save(temp_docx_path) temp_pdf_path = temp_docx_path.replace('.docx', '.pdf') convert(temp_docx_path) # Convert to PDF os.rename(temp_docx_path.replace('.docx', '.pdf'), temp_pdf_path) # Append PDFs combined_pdf_path = temp_pdf_path.replace('.pdf', '_combined.pdf') append_pdfs([BEFORE_PDF_PATH, temp_pdf_path, AFTER_PDF_PATH], combined_pdf_path) # Clean up os.remove(temp_pdf_path) # Remove temp PDF after combining print(f"Saved combined document: {combined_pdf_path}") return combined_pdf_pathdef combine_documents(document_paths, output_pdf_path): """Combine multiple PDF documents into a single PDF document.""" append_pdfs(document_paths, output_pdf_path)
def populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs = []
# Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Combine all individual documents into one combine_documents(individual_docs, output_path) # Clean up temporary documents for doc_path in individual_docs: os.remove(doc_path) print("Temporary documents cleaned up.") except Exception as e: print(f"Unexpected error: {e}")Streamlit application
def main(): st.title("Fill Chambers and Partners Form")
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.pdf" populate_chambers(excel_file, output_path) st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.pdf", mime="application/pdf" ) else: st.error("Please upload the Excel file.")if name == "main": main() with this code
- Assistant
Certainly! Here is the complete updated code, which integrates your requirements for generating documents based on Excel input, appending pages from specified PDF files, and handling the output in a Streamlit application.
Make sure to replace the template and PDF file paths with the actual paths on your system before running the code.
import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st from PyPDF2 import PdfReader, PdfWriter from docx2pdf import convert # Ensure to install docx2pdf if you want to convert DOCX to PDF # Paths to the Word templates and PDFs TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows BEFORE_PDF_PATH = r"C:\Administrator\Desktop\new\before.pdf" AFTER_PDF_PATH = r"C:\Administrator\Desktop\new\After.pdf" # Function to append PDFs def append_pdfs(pdf_list, output_pdf): writer = PdfWriter() for pdf in pdf_list: reader = PdfReader(pdf) for page in range(len(reader.pages)): writer.add_page(reader.pages[page]) with open(output_pdf, 'wb') as f: writer.write(f) def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path) # Identifying text based on template type if "Confidential" in template_path: identifier_text = f"Confidential Matter {matter_count}" else: identifier_text = f"Publishable Matter {matter_count}" # Update the table cell with matter count existing_text = doc.tables[0].cell(1, 0).text if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" # Save the document temporarily and convert it to PDF temp_docx_path = output_path doc.save(temp_docx_path) temp_pdf_path = temp_docx_path.replace('.docx', '.pdf') convert(temp_docx_path) # Convert to PDF os.rename(temp_docx_path.replace('.docx', '.pdf'), temp_pdf_path) # Append PDFs combined_pdf_path = temp_pdf_path.replace('.pdf', '_combined.pdf') append_pdfs([BEFORE_PDF_PATH, temp_pdf_path, AFTER_PDF_PATH], combined_pdf_path) # Clean up os.remove(temp_pdf_path) # Remove temp PDF after combining print(f"Saved combined document: {combined_pdf_path}") return combined_pdf_path def combine_documents(document_paths, output_pdf_path): """Combine multiple PDF documents into a single PDF document.""" append_pdfs(document_paths, output_pdf_path) def populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs = [] # Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Combine all individual documents into one combine_documents(individual_docs, output_path) # Clean up temporary documents for doc_path in individual_docs: os.remove(doc_path) print("Temporary documents cleaned up.") except Exception as e: print(f"Unexpected error: {e}") # Streamlit application def main(): st.title("Fill Chambers and Partners Form") excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.pdf" populate_chambers(excel_file, output_path) # Check if the output file was created successfully if os.path.exists(output_path): st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.pdf", mime="application/pdf" ) else: st.error("Failed to create the PDF file.") else: st.error("Please upload the Excel file.") if __name__ == "__main__": main()Key Components of the Code:
-
PDF Generation: The function
create_individual_documentcreates a Word document, populates it with data, converts it to PDF, and then appends the specifiedbefore.pdfandafter.pdffiles to it. -
Document Combining: The
combine_documentsfunction combines all generated PDF documents into one single PDF for download. -
Streamlit Interaction: The main function creates a web interface where users can upload an Excel file, generate the documents, and then download the final combined PDF.
Important Notes:
- Ensure you have the required libraries (
pandas,python-docx,PyPDF2,docx2pdf, andstreamlit) installed in your Python environment. - Adjust the template paths (
TEMPLATE_PATH_NO,TEMPLATE_PATH_YES,BEFORE_PDF_PATH,AFTER_PDF_PATH) to correct file locations on your machine. - If running in a new environment, you will need to install the dependencies using
pipas follows:pip install pandas python-docx PyPDF2 docx2pdf streamlit
With this code, you should be able to successfully generate the required PDF reports, integrating the first and last pages as specified. If you encounter any issues, please make sure to check for relevant error messages in the console and debug accordingly.
-
- User
0%| | 0/1 [00:00<?, ?it/s]Unexpected error: Open.SaveAs 0%| failed to save pdf file
- Assistant
The error message "Open.SaveAs failed to save PDF file" indicates that there is an issue with converting the DOCX file to PDF using the
docx2pdflibrary. This can happen due to several reasons, such as issues with file permissions, the path specified, or the Office installation required bydocx2pdf.Here are some steps to troubleshoot and fix this issue:
1. Installation Verification:
Make sure that you have Microsoft Word installed because
docx2pdfuses Word's COM interface to perform the conversion. If it’s not installed, please install it.2. File Paths:
Ensure that the file paths you are using for saving are correct and that you have permissions to write to those directories.
3. Change Output Path:
Instead of using a temporary path in the same directory, try specifying a full path for the PDF output where you know you have write permission. For instance:
temp_pdf_path = r"C:\Users\Administrator\Desktop\temp_output.pdf" # Example path4. Check for Open Documents:
Make sure there isn’t an instance of Microsoft Word that is already running in the background. Sometimes, if Word is open and locked up or running a different process,
docx2pdfcannot save files.5. Update Your Code:
Here’s an updated snippet that includes error handling around the PDF conversion process. This adjustment will help you catch the specific errors and handle them accordingly:
import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st from PyPDF2 import PdfReader, PdfWriter from docx2pdf import convert # Ensure to install docx2pdf if you want to convert DOCX to PDF # Paths to the Word templates and PDFs TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows BEFORE_PDF_PATH = r"C:\Administrator\Desktop\new\before.pdf" AFTER_PDF_PATH = r"C:\Administrator\Desktop\new\After.pdf" # Function to append PDFs def append_pdfs(pdf_list, output_pdf): writer = PdfWriter() for pdf in pdf_list: reader = PdfReader(pdf) for page in range(len(reader.pages)): writer.add_page(reader.pages[page]) with open(output_pdf, 'wb') as f: writer.write(f) def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path) # Identifying text based on template type if "Confidential" in template_path: identifier_text = f"Confidential Matter {matter_count}" else: identifier_text = f"Publishable Matter {matter_count}" # Update the table cell with matter count existing_text = doc.tables[0].cell(1, 0).text if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" # Save the document temporarily temp_docx_path = output_path doc.save(temp_docx_path) # Convert to PDF with error handling temp_pdf_path = temp_docx_path.replace('.docx', '.pdf') try: convert(temp_docx_path) # Convert to PDF os.rename(temp_docx_path.replace('.docx', '.pdf'), temp_pdf_path) except Exception as e: print(f"Error converting DOCX to PDF: {e}") raise # Append PDFs combined_pdf_path = temp_pdf_path.replace('.pdf', '_combined.pdf') append_pdfs([BEFORE_PDF_PATH, temp_pdf_path, AFTER_PDF_PATH], combined_pdf_path) # Clean up os.remove(temp_pdf_path) # Remove temp PDF after combining print(f"Saved combined document: {combined_pdf_path}") return combined_pdf_path # The rest of your code remains unchanged... def combine_documents(document_paths, output_pdf_path): """Combine multiple PDF documents into a single PDF document.""" append_pdfs(document_paths, output_pdf_path) def populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs = [] # Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" combined_pdf_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs.append(combined_pdf_path) # Combine all individual documents into one combine_documents(individual_docs, output_path) # Clean up temporary documents for doc_path in individual_docs: os.remove(doc_path) print("Temporary documents cleaned up.") except Exception as e: print(f"Unexpected error: {e}") # Streamlit application def main(): st.title("Fill Chambers and Partners Form") excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.pdf" populate_chambers(excel_file, output_path) # Check if the output file was created successfully if os.path.exists(output_path): st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.pdf", mime="application/pdf" ) else: st.error("Failed to create the PDF file.") else: st.error("Please upload the Excel file.") if __name__ == "__main__": main()Summary of Changes:
- An exception handling block has been added around the PDF conversion (
convert) call to catch and display errors that occur during the conversion process. - Consider specifying full paths for temporary and output files to avoid issues with file access.
- Ensure that the program’s execution environment has all prerequisites satisfied, particularly Microsoft Word.
Make sure to review the console for any specific error messages output by the error handling, as these will help pinpoint the issue further. If the error persists, you may want to consider alternative ways to convert DOCX to PDF, such as using another library if you're unable to resolve the issue with
docx2pdf. - An exception handling block has been added around the PDF conversion (
- User
we dont have to make pdf ...i wnated doc
- Assistant
I see! If you want to create and combine
.docx(Word) files instead of converting to PDF, we can adjust the code accordingly. Below is the modified code that generates individual.docxfiles based on the provided Excel data and appends thebefore.docxandafter.docxfiles (assuming you want to use.docxfor both).Here's the updated code:
import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st # Paths to the Word templates and additional DOCX files TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows BEFORE_DOCX_PATH = r"C:\Administrator\Desktop\new\before.docx" AFTER_DOCX_PATH = r"C:\Administrator\Desktop\new\after.docx" # Function to append Word documents def append_docs(doc_list, output_doc): combined_doc = Document() for doc in doc_list: sub_doc = Document(doc) for element in sub_doc.element.body: combined_doc.element.body.append(element) combined_doc.save(output_doc) def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path) # Identifying text based on template type if "Confidential" in template_path: identifier_text = f"Confidential Matter {matter_count}" else: identifier_text = f"Publishable Matter {matter_count}" # Update the table cell with matter count existing_text = doc.tables[0].cell(1, 0).text if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" # Save the individual document doc.save(output_path) print(f"Saved individual document: {output_path}") return output_path # Return path for later combining def populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs = [] # Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs.append(individual_doc_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs.append(individual_doc_path) # Combine all individual documents into one, with additional DOCX files final_output_path = output_path append_docs([BEFORE_DOCX_PATH] + individual_docs + [AFTER_DOCX_PATH], final_output_path) print(f"Combined document saved: {final_output_path}") # Clean up temporary documents for doc_path in individual_docs: os.remove(doc_path) except Exception as e: print(f"Unexpected error: {e}") # Streamlit application def main(): st.title("Fill Chambers and Partners Form") excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.docx" populate_chambers(excel_file, output_path) # Check if the output file was created successfully if os.path.exists(output_path): st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) else: st.error("Failed to create the DOCX file.") else: st.error("Please upload the Excel file.") if __name__ == "__main__": main()Key Changes in This Code:
-
Document Combination: The
append_docsfunction has been retained to combine multiple Word documents instead of PDFs. -
No PDF Conversion: Removed all reference to PDF conversion, instead focusing on creating
.docxdocuments. -
Streamlit Handling: The file download will now be for
.docxdocuments.
Notes:
- Before running the code, ensure that the file paths for your template and additional documents (
BEFORE_DOCX_PATH,AFTER_DOCX_PATH) are correct and pointing to existing.docxfiles. - Also, make sure to install required libraries if you haven't yet:
pip install pandas python-docx streamlit
This modified code will generate individual Word documents based on the data from the uploaded Excel file, and combine them with your specified before and after documents directly into a final
.docxoutput. -
- User
import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st
Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows BEFORE_DOCX_PATH = r"C:\Administrator\Desktop\new\before.docx" AFTER_DOCX_PATH = r"C:\Administrator\Desktop\new\After.docx"
Function to append Word documents
def append_docs(doc_list, output_doc): combined_doc = Document()
for doc in doc_list: sub_doc = Document(doc) for element in sub_doc.element.body: combined_doc.element.body.append(element) combined_doc.save(output_doc)def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path)
# Identifying text based on template type if "Confidential" in template_path: identifier_text = f"Confidential Matter {matter_count}" else: identifier_text = f"Publishable Matter {matter_count}" # Update the table cell with matter count existing_text = doc.tables[0].cell(1, 0).text if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" # Save the individual document doc.save(output_path) print(f"Saved individual document: {output_path}") return output_path # Return path for later combiningdef populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs = []
# Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs.append(individual_doc_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs.append(individual_doc_path) # Combine all individual documents into one, with additional DOCX files final_output_path = output_path append_docs([BEFORE_DOCX_PATH] + individual_docs + [AFTER_DOCX_PATH], final_output_path) print(f"Combined document saved: {final_output_path}") # Clean up temporary documents for doc_path in individual_docs: os.remove(doc_path) except Exception as e: print(f"Unexpected error: {e}")Streamlit application
def main(): st.title("Fill Chambers and Partners Form")
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.docx" populate_chambers(excel_file, output_path) # Check if the output file was created successfully if os.path.exists(output_path): st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) else: st.error("Failed to create the DOCX file.") else: st.error("Please upload the Excel file.")if name == "main": main() in this after filling the yes and no templatees combine before then no and then after then yes all together
- Assistant
To modify your code so that the final document combines
before.docx, all "No" row documents, followed byafter.docx, and then all "Yes" row documents, you'll need to adjust the order in which you append the documents in thepopulate_chambersfunction.Here’s the updated code to achieve that:
import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st # Paths to the Word templates and additional DOCX files TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows BEFORE_DOCX_PATH = r"C:\Administrator\Desktop\new\before.docx" AFTER_DOCX_PATH = r"C:\Administrator\Desktop\new\after.docx" # Function to append Word documents def append_docs(doc_list, output_doc): combined_doc = Document() for doc in doc_list: sub_doc = Document(doc) for element in sub_doc.element.body: combined_doc.element.body.append(element) combined_doc.save(output_doc) def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path) # Identifying text based on template type if "Confidential" in template_path: identifier_text = f"Confidential Matter {matter_count}" else: identifier_text = f"Publishable Matter {matter_count}" # Update the table cell with matter count existing_text = doc.tables[0].cell(1, 0).text if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" # Save the individual document doc.save(output_path) print(f"Saved individual document: {output_path}") return output_path # Return path for later combining def populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs_no = [] individual_docs_yes = [] # Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs_no.append(individual_doc_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs_yes.append(individual_doc_path) # Combine in the desired order: before + No documents + after + Yes documents final_output_path = output_path append_docs([BEFORE_DOCX_PATH] + individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, final_output_path) print(f"Combined document saved: {final_output_path}") # Clean up temporary documents for doc_path in individual_docs_no + individual_docs_yes: os.remove(doc_path) except Exception as e: print(f"Unexpected error: {e}") # Streamlit application def main(): st.title("Fill Chambers and Partners Form") excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.docx" populate_chambers(excel_file, output_path) # Check if the output file was created successfully if os.path.exists(output_path): st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) else: st.error("Failed to create the DOCX file.") else: st.error("Please upload the Excel file.") if __name__ == "__main__": main()Key Changes Made:
-
Document Lists: I created two separate lists:
individual_docs_no: to hold document paths for the "No" rows.individual_docs_yes: to hold document paths for the "Yes" rows.
-
Combining Order: Changed the order of appending documents in the
append_docsfunction call to:[BEFORE_DOCX_PATH] + individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes
This ensures that your final document structure will be:
- Content of
before.docx - Individual documents filled from "No" rows
- Content of
after.docx - Individual documents filled from "Yes" rows
Other Notes:
- Ensure that your template paths and the before and after document paths are correct.
- Make sure the necessary libraries (
pandas,python-docx,streamlit) are installed in your Python environment. You can do this using:pip install pandas python-docx streamlit
With these changes, the application should work as expected to combine the documents in the specified order. If you have any further modifications or requirements, feel free to ask!
-
- User
import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st
Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows BEFORE_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\before.docx" AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
Function to append Word documents
def append_docs(doc_list, output_doc): combined_doc = Document()
for doc in doc_list: sub_doc = Document(doc) for element in sub_doc.element.body: combined_doc.element.body.append(element) combined_doc.save(output_doc)def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path)
# Identifying text based on template type if "Confidential" in template_path: identifier_text = f"Confidential Matter {matter_count}" else: identifier_text = f"Publishable Matter {matter_count}" # Update the table cell with matter count existing_text = doc.tables[0].cell(1, 0).text if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" # Save the individual document doc.save(output_path) print(f"Saved individual document: {output_path}") return output_path # Return path for later combiningdef populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs_no = [] individual_docs_yes = []
# Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs_no.append(individual_doc_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs_yes.append(individual_doc_path) # Combine in the desired order: before + No documents + after + Yes documents final_output_path = output_path append_docs([BEFORE_DOCX_PATH] + individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, final_output_path) print(f"Combined document saved: {final_output_path}") # Clean up temporary documents for doc_path in individual_docs_no + individual_docs_yes: os.remove(doc_path) except Exception as e: print(f"Unexpected error: {e}")Streamlit application
def main(): st.title("Fill Chambers and Partners Form")
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.docx" populate_chambers(excel_file, output_path) # Check if the output file was created successfully if os.path.exists(output_path): st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) else: st.error("Failed to create the DOCX file.") else: st.error("Please upload the Excel file.")if name == "main": main() from this remove berfore docs
- Assistant
Certainly! To adjust your code so that it generates the combined document without including the
before.docxfile, you simply need to modify the document appending part in thepopulate_chambersfunction. We will removeBEFORE_DOCX_PATHfrom the list of documents to be combined.Here’s the updated code:
import pandas as pd from docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st # Paths to the Word templates and additional DOCX files TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\after.docx" # Function to append Word documents def append_docs(doc_list, output_doc): combined_doc = Document() for doc in doc_list: sub_doc = Document(doc) for element in sub_doc.element.body: combined_doc.element.body.append(element) combined_doc.save(output_doc) def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path) # Identifying text based on template type if "Confidential" in template_path: identifier_text = f"Confidential Matter {matter_count}" else: identifier_text = f"Publishable Matter {matter_count}" # Update the table cell with matter count existing_text = doc.tables[0].cell(1, 0).text if "Matter" in existing_text: parts = existing_text.split(" ") parts[-1] = str(matter_count) doc.tables[0].cell(1, 0).text = " ".join(parts) else: doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}" doc.tables[0].cell(4, 0).text = f" {data['Value ']}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}" doc.tables[0].cell(7, 0).text = f" {data['Team Members']}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}" # Save the individual document doc.save(output_path) print(f"Saved individual document: {output_path}") return output_path # Return path for later combining def populate_chambers(excel_file, output_path): """Generate the documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs_no = [] individual_docs_yes = [] # Filter the DataFrame for rows df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] # Handle Publishable Matters for 'No' rows for index, row in df_no.iterrows(): temporary_output_path = f"temp_publishable_no_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path) individual_docs_no.append(individual_doc_path) # Handle Publishable Matters for 'Yes' rows for index, row in df_yes.iterrows(): temporary_output_path = f"temp_publishable_yes_{index}.docx" individual_doc_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path) individual_docs_yes.append(individual_doc_path) # Combine in the desired order: No documents + after + Yes documents final_output_path = output_path append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, final_output_path) print(f"Combined document saved: {final_output_path}") # Clean up temporary documents for doc_path in individual_docs_no + individual_docs_yes: os.remove(doc_path) except Exception as e: print(f"Unexpected error: {e}") # Streamlit application def main(): st.title("Fill Chambers and Partners Form") excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"]) if st.button("Fill the Template"): if excel_file: output_path = "combined_confidential_publishable.docx" populate_chambers(excel_file, output_path) # Check if the output file was created successfully if os.path.exists(output_path): st.success("Forms filled successfully!") # Provide download link with open(output_path, "rb") as f: btn = st.download_button( label="Download Filled Form", data=f, file_name="combined_confidential_publishable.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) else: st.error("Failed to create the DOCX file.") else: st.error("Please upload the Excel file.") if __name__ == "__main__": main()Changes Made:
- Removal of
BEFORE_DOCX_PATH: The line that includedBEFORE_DOCX_PATHin the append list has been removed. - Order of Combination: The new order is:
- First, the individual documents filled from the "No" rows.
- Followed directly by
after.docx. - Then, the individual documents filled from the "Yes" rows.
This will combine all relevant documents in the required order without including the
before.docxfile.Additional Considerations:
- Ensure that all your Word templates and input documents exist at the specified paths.
- Test the application thoroughly to ensure it meets your requirements and that all data is populated correctly in the output document.
- Removal of