If you're still encountering empty pages at the beginning of the merged document, there are a few possible factors to consider.
-
Initial Blank Paragraph: When a new Document is created, it may automatically include a blank paragraph. If the first document being merged isn't empty, it could end up pushing that first paragraph into a new page if the layout of the document adds space.
-
Page Break Handling: If any of the documents being merged have their own page breaks, it can cause undesired spacing.
To address these issues, we'll implement the following adjustments in the combine_word_documents function:
-
Trim Empty Paragraphs and Leading Spaces: Ensure any initial blank paragraphs are properly handled. We'll check for and remove empty paragraphs after copying.
-
Adding Content Only: Ensure there's sanity checking on documents we're trying to merge to ensure we only copy non-empty content.
Here’s how we can modify the combine_word_documents function:
Updated combine_word_documents Function
def combine_word_documents(files, output_path):
"""
Combines multiple Word documents into one,
ensuring no initial blank page is created.
The first file becomes the base document, and each subsequent file's content is added to it.
"""
if not files:
print("No files to combine.")
return
print(f"Combining {len(files)} documents...")
# Create a new document for merging
merged_document = Document()
for i, file in enumerate(files):
print(f"Adding content from {file}")
try:
sub_doc = Document(file)
# Check if the document has paragraphs to avoid adding empty documents
if len(sub_doc.paragraphs) > 0:
# If it's not the first document, add a page break before adding content
if i > 0:
merged_document.add_page_break()
# Copy all elements from the subdocument without adding empty paragraphs
for element in sub_doc.element.body:
# Don't copy the section break
if element.tag != qn('w:sectPr'):
merged_document.element.body.append(element)
# Remove leading empty paragraphs from the merged document
while merged_document.paragraphs and merged_document.paragraphs[0].text == '':
p = merged_document.paragraphs[0]._element
p.getparent().remove(p)
p._p = p._element = None
else:
print(f"Warning: Document {file} is empty and will not be added.")
except Exception as e:
print(f"Warning: Could not add content from {file}: {e}")
# Save the combined document
merged_document.save(output_path)
print(f"Combined document saved to {output_path}")
Key Changes Made:
-
Handling Empty Paragraphs After Merging: A loop checks for any leading empty paragraphs in the merged_document and removes them after copying content from each document.
-
Handling Page Breaks: Page breaks are still added between documents, but we ensure we don't introduce any extra content or empty paragraphs that could lead to an unexpected empty page.
Complete Updated Code
Now, let’s integrate this updated combine_word_documents function with the full code:
import pandas as pd
from docx import Document
from docx.shared import RGBColor, Pt
import os
from docx.oxml.ns import qn
import streamlit as st
# Hardcoded paths for the Word templates
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Iflr_Yes.docx" # Template for Yes rows
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Iflr_No.docx" # Template for No rows
def populate_chambers(excel_path, output_path):
try:
print("Loading Excel data...")
df = pd.read_excel(excel_path)
print(f"Excel data loaded: {len(df)} rows")
# Variables to keep track of counts of documents
confidential_count = 0
non_confidential_count = 0
# Create directories for temporary files if they don't exist
temp_dir = os.path.join(os.path.dirname(output_path), "temp")
os.makedirs(temp_dir, exist_ok=True)
yes_files = []
no_files = []
# Iterate through each row of the DataFrame
for i, row in df.iterrows():
# Determine which document to use based on the Confidential/Publishable column
confidential_val = str(row.get('Confidential / Publishable ', '')).strip()
if confidential_val.lower() == 'yes' and confidential_count < 10:
confidential_count += 1
# Create a new document from the template for each row
doc = Document(TEMPLATE_PATH_YES)
if doc.tables:
table = doc.tables[0] # Use the first table in the template
fill_table_with_data(row, table, True, confidential_count)
# Save as temporary file
temp_file = os.path.join(temp_dir, f"yes_{i}.docx")
doc.save(temp_file)
yes_files.append(temp_file)
print(f"Created 'Yes' document for row {confidential_count}")
else:
print(f"Warning: No tables found in the 'Yes' template.")
elif confidential_val.lower() == 'no' and non_confidential_count < 10:
non_confidential_count += 1
# Create a new document from the template for each row
doc = Document(TEMPLATE_PATH_NO)
if doc.tables:
table = doc.tables[0] # Use the first table in the template
fill_table_with_data(row, table, False, non_confidential_count)
# Save as temporary file
temp_file = os.path.join(temp_dir, f"no_{i}.docx")
doc.save(temp_file)
no_files.append(temp_file)
print(f"Created 'No' document for row {non_confidential_count}")
else:
print(f"Warning: No tables found in the 'No' template.")
else:
print(f"Warning: Maximum limit reached for {'confidential' if confidential_val.lower() == 'yes' else 'non-confidential'} documents or unexpected value in the 'Confidential / Publishable ' column: {confidential_val}.")
# Combine all documents: 'No' files followed by 'Yes' files
combine_word_documents(no_files + yes_files, output_path)
print(f"All documents combined successfully to {output_path}!")
# Clean up temporary files
for file in no_files + yes_files:
try:
os.remove(file)
except Exception as e:
print(f"Warning: Could not delete temporary file {file}: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def fill_table_with_data(row, table, is_confidential, count):
try:
if len(table.rows) >= 25: # Make sure the table has enough rows
# Fill cell 0 with the format "Example x/10"
fill_cell(table.cell(0, 0), f"Example {min(count, 10)}/10", is_confidential, style='special')
fill_cell(table.cell(2, 0), 'Y' if is_confidential else 'N', is_confidential) # Cell 2 filled with 'Y' or 'N'
fill_cell(table.cell(4, 0), str(row['Client Name ']), is_confidential) # Client Name
fill_cell(table.cell(14, 0), str(row['Value ']), is_confidential) # Matter/Case Overview
fill_cell(table.cell(20, 0), str(row['Lead partners']), is_confidential) # Lead Partner
fill_cell(table.cell(22, 0), str(row['Other Firms/counsels Involved']), is_confidential) # Other Involved Firms
fill_cell(table.cell(24, 0), str(row['Description (in 500 words)']), is_confidential) # Description
print(f"Table filled with {'Yes' if is_confidential else 'No'} form data.")
else:
print(f"Warning: Table has only {len(table.rows)} rows. Expected at least 25.")
except IndexError as e:
print(f"Error: Unable to fill the table. {e}")
def fill_cell(cell, text, is_confidential, style=None):
# Clear existing content by deleting each paragraph
for paragraph in cell.paragraphs:
cell._element.remove(paragraph._element)
# Adding a new paragraph to the cell
p = cell.add_paragraph()
run = p.add_run(text)
if style == 'special':
# Applying the special style
run.font.size = Pt(14) # Font size 14
run.bold = True # Bold
run.font.name = 'Cambria' # Font family
run.font.color.rgb = RGBColor(255, 255, 255) # White color
p.alignment = 1 # Centre alignment
else:
if is_confidential:
run.font.color.rgb = RGBColor(255, 0, 0) # Set the font color to red
else:
run.font.color.rgb = RGBColor(0, 0, 0) # Default font color
# Set font name for all text in the cell
for run in p.runs:
run.font.name = 'Cambria'
def combine_word_documents(files, output_path):
"""
Combines multiple Word documents into one,
ensuring no initial blank page is created.
The first file becomes the base document, and each subsequent file's content is added to it.
"""
if not files:
print("No files to combine.")
return
print(f"Combining {len(files)} documents...")
# Create a new document for merging
merged_document = Document()
for i, file in enumerate(files):
print(f"Adding content from {file}")
try:
sub_doc = Document(file)
# Check if the document has paragraphs to avoid adding empty documents
if len(sub_doc.paragraphs) > 0:
# If it's not the first document, add a page break before adding content
if i > 0:
merged_document.add_page_break()
# Copy all elements from the subdocument without adding empty paragraphs
for element in sub_doc.element.body:
# Don't copy the section break
if element.tag != qn('w:sectPr'):
merged_document.element.body.append(element)
# Remove leading empty paragraphs from the merged document
while merged_document.paragraphs and merged_document.paragraphs[0].text == '':
p = merged_document.paragraphs[0]._element
p.getparent().remove(p)
p._p = p._element = None
else:
print(f"Warning: Document {file} is empty and will not be added.")
except Exception as e:
print(f"Warning: Could not add content from {file}: {e}")
# Save the combined document
merged_document.save(output_path)
print(f"Combined document saved to {output_path}")
# Streamlit application
def main():
st.title("IFLR 1000 Form Generator")
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
with st.spinner("Processing..."):
# Save the uploaded Excel file temporarily
temp_excel_path = "temp_uploaded_file.xlsx"
with open(temp_excel_path, "wb") as f:
f.write(excel_file.getbuffer())
# Output path
output_file = r"C:\Users\Administrator\Desktop\output.docx"
# Call the populate_chambers function
populate_chambers(temp_excel_path, output_file)
# Provide a link to download the output file
if os.path.exists(output_file):
st.success("Forms filled successfully! You can download it below.")
with open(output_file, "rb") as f:
st.download_button(
"Download Filled Form",
f,
file_name="IFLR_Output.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the output file.")
# Clean up the temporary file
os.remove(temp_excel_path)
else:
st.error("Please upload the Excel file.")
if __name__ == "__main__":
main()
Test the Updated Code
Please run this updated code, and check to see if the issue with empty pages at the start of the merged document has been resolved. If issues persist, it might help to inspect the individual document contents, ensuring they are structured correctly and do not contain unintended formatting or spacing that could lead to these empty pages.