import streamlit as st
import pandas as pd
from docx import Document
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
import io
from docx2pdf import convert as docx2pdf_convert
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_TAB_ALIGNMENT, WD_TAB_LEADER, WD_BREAK
import tempfile
import os
import re
Function to convert docx bytes to PDF bytes
def convert_docx_to_pdf(docx_bytes):
with tempfile.TemporaryDirectory() as tmpdir:
docx_path = os.path.join(tmpdir, "temp.docx")
pdf_path = os.path.join(tmpdir, "temp.pdf")
with open(docx_path, "wb") as f:
f.write(docx_bytes)
docx2pdf_convert(docx_path, pdf_path)
with open(pdf_path, "rb") as f:
pdf_bytes = f.read()
return pdf_bytes
st.title("📄 Word Mail Merge Application")
Helper for file signature checking
def is_valid_docx(file):
try:
file.seek(0)
sig = file.read(4)
file.seek(0)
return sig == b'PK\x03\x04'
except Exception:
return False
Convert any Word (.docx) file to PDF
st.subheader("Convert any Word (.docx) file to PDF")
docx_for_pdf = st.file_uploader("Upload a Word (.docx) file to convert to PDF", type=["docx"], key="pdfconvert")
if docx_for_pdf:
docx_filename = docx_for_pdf.name if hasattr(docx_for_pdf, 'name') else ''
if not docx_filename.lower().endswith('.docx'):
st.error("Please upload a valid Word (.docx) file. Upload cancelled.")
st.stop()
if not is_valid_docx(docx_for_pdf):
st.error("The uploaded file is not a valid Word (.docx) file. Upload cancelled.")
st.stop()
docx_bytes = docx_for_pdf.read()
with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as tmp_docx:
tmp_docx.write(docx_bytes)
tmp_docx_path = tmp_docx.name
try:
Document(tmp_docx_path)
except Exception:
st.error("The uploaded file cannot be opened as a Word document. Upload cancelled.")
os.remove(tmp_docx_path)
st.stop()
os.remove(tmp_docx_path)
if st.button("Convert uploaded Word file to PDF"):
try:
pdf_bytes = convert_docx_to_pdf(docx_bytes)
st.download_button("📥 Download converted PDF", pdf_bytes, file_name="converted_output.pdf")
except Exception as e:
st.error(f"Conversion failed: The uploaded file is not a usable Word document. Error: {e}")
attachment_columns = [
("Q23 - Attachment 1 (optional) - Id", "Q23 - Attachment 1 (optional)"),
("Q24 - Attachment 2 (optional) - Id", "Q24 - Attachment 2 (optional)"),
("Q23_Id", "Q23 - Attachment 1 (optional)"),
("Q24_Id", "Q24 - Attachment 2 (optional)")
]
cols_to_drop = []
insert_instructions = []
for old_col, new_col in attachment_columns:
if old_col in df.columns:
pos = df.columns.get_loc(old_col)
df[new_col] = df[old_col].apply(lambda x: f"https://hkbuchtl.qualtrics.com/Q/File.php?F={x}" if pd.notnull(x) and str(x).strip() != '' else '')
cols_to_drop.append(old_col)
insert_instructions.append((new_col, pos))
if cols_to_drop:
df = df.drop(columns=cols_to_drop)
for new_col, pos in sorted(insert_instructions, key=lambda x: x[1]):
col = df.pop(new_col)
df.insert(pos, new_col, col)
for col in df.columns:
if pd.api.types.is_datetime64_any_dtype(df[col]):
df[col] = df[col].dt.strftime('%d %b %Y')
else:
try:
df[col] = pd.to_datetime(df[col]).dt.strftime('%d %b %Y')
except Exception:
pass
df = df.fillna("")
st.subheader("Preview of Processed Data")
st.dataframe(df)
Process mail merge if both files are uploaded
if excel_file and template_file:
code
try:
template_doc = Document(template_file)
except Exception as e:
st.error(f"Error reading Word template file: {e}")
st.stop()
# Use the template as the base for the merged document to preserve section/spacing settings
merged_doc = Document(template_file)
# Remove all content from merged_doc but keep section settings
for _ in range(len(merged_doc.paragraphs)):
p = merged_doc.paragraphs[0]
p._element.getparent().remove(p._element)
for _ in range(len(merged_doc.tables)):
t = merged_doc.tables[0]
t._element.getparent().remove(t._element)
toc_entries = []
current_page = 1 # Start on page 1 (TOC)
# Add TOC title with bookmark
toc_title = merged_doc.add_paragraph()
toc_bookmark = OxmlElement('w:bookmarkStart')
toc_bookmark_id = "toc_bookmark"
toc_bookmark.set(qn('w:id'), '1')
toc_bookmark.set(qn('w:name'), toc_bookmark_id)
toc_title._p.insert(0, toc_bookmark)
toc_bookmark_end = OxmlElement('w:bookmarkEnd')
toc_bookmark_end.set(qn('w:id'), '1')
toc_title._p.append(toc_bookmark_end)
toc_title_run = toc_title.add_run("Table of Contents")
toc_title_run.bold = True
toc_title_run.font.size = Pt(16)
toc_title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Process records to collect TOC entries
bookmark_counter = 2
for i, row in df.iterrows():
record_page = current_page + 1 # Content starts after TOC
record_title = None
record_bookmark = f"record_{i+1}"
for para in template_doc.paragraphs:
is_heading = para.style.name.startswith('Heading')
heading_level = 0
if is_heading:
try:
heading_level = int(para.style.name.replace('Heading ', ''))
except ValueError:
heading_level = 1
full_text = para.text if para.text is not None else ""
for col in df.columns:
placeholder = f"{{{{{col}}}}}"
full_text = full_text.replace(placeholder, str(row[col]))
if full_text.strip():
full_text = re.sub(r'[ \t]+', ' ', full_text.strip())
else:
full_text = ""
if is_heading and full_text.strip():
if record_title is None:
record_title = full_text
heading_bookmark = record_bookmark
else:
heading_bookmark = f"heading_{bookmark_counter}"
bookmark_counter += 1
toc_entries.append((full_text, heading_level, record_page, heading_bookmark))
if record_title is None:
record_title = f"Record {i+1}" if not df.columns.empty else str(row[df.columns[0]])
if record_title not in [entry[0] for entry in toc_entries]:
toc_entries.append((record_title, 1, record_page, record_bookmark))
current_page += 1
# Generate TOC with hyperlinks
for text, level, page, bookmark in toc_entries:
toc_entry = merged_doc.add_paragraph()
toc_entry.paragraph_format.left_indent = Pt(level * 12)
hyperlink_run = toc_entry.add_run()
hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('w:anchor'), bookmark)
hyperlink_text = OxmlElement('w:r')
rPr = OxmlElement('w:rPr')
color = OxmlElement('w:color')
color.set(qn('w:val'), '0000FF')
rPr.append(color)
u = OxmlElement('w:u')
u.set(qn('w:val'), 'single')
rPr.append(u)
hyperlink_text.append(rPr)
t = OxmlElement('w:t')
t.text = text
hyperlink_text.append(t)
hyperlink.append(hyperlink_text)
hyperlink_run._r.append(hyperlink)
toc_entry.add_run("\t" + str(page))
tab_stops = toc_entry.paragraph_format.tab_stops
tab_stops.add_tab_stop(Pt(450), WD_TAB_ALIGNMENT.RIGHT, WD_TAB_LEADER.DOTS)
# Add page break after TOC using XML to ensure reliability
toc_last_para = merged_doc.add_paragraph()
run = toc_last_para.add_run()
br = OxmlElement('w:br')
br.set(qn('w:type'), 'page')
run._r.append(br)
# Add content with bookmarks and "Back to TOC" links
for i, row in df.iterrows():
record_bookmark = f"record_{i+1}"
record_added = False
for para in template_doc.paragraphs:
new_para = merged_doc.add_paragraph()
new_para.style = para.style
is_heading = para.style.name.startswith('Heading')
if not record_added:
bookmark = OxmlElement('w:bookmarkStart')
bookmark.set(qn('w:id'), str(i + 2))
bookmark.set(qn('w:name'), record_bookmark)
new_para._p.insert(0, bookmark)
bookmark_end = OxmlElement('w:bookmarkEnd')
bookmark_end.set(qn('w:id'), str(i + 2))
new_para._p.append(bookmark_end)
record_added = True
full_text = para.text if para.text is not None else ""
for col in df.columns:
placeholder = f"{{{{{col}}}}}"
value = str(row[col])
# Preserve line breaks in the value
value = value.replace('\r\n', '\n').replace('\r', '\n')
full_text = full_text.replace(placeholder, value)
if full_text.strip():
# Remove only extra spaces/tabs, but preserve line breaks
full_text = re.sub(r'[ \t]+', ' ', full_text)
lines = full_text.split('\n')
else:
lines = []
if lines:
while new_para.runs:
new_para.runs[0]._element.getparent().remove(new_para.runs[0]._element)
if para.runs:
run = para.runs[0]
for idx, line in enumerate(lines):
new_run = new_para.add_run(line.strip())
new_run.bold = run.bold
new_run.italic = run.italic
new_run.underline = run.underline
new_run.font.color.rgb = run.font.color.rgb
new_run.font.size = run.font.size
new_run.font.name = run.font.name
new_run.font.highlight_color = run.font.highlight_color
new_run.font.superscript = run.font.superscript
new_run.font.subscript = run.font.subscript
if idx < len(lines) - 1:
new_run.add_break(WD_BREAK.LINE)
else:
for idx, line in enumerate(lines):
run = new_para.add_run(line.strip())
if idx < len(lines) - 1:
run.add_break(WD_BREAK.LINE)
new_para.alignment = para.alignment
else:
new_para._element.getparent().remove(new_para._element)
# Add "Back to TOC" link
back_link_para = merged_doc.add_paragraph()
back_link_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
back_link_run = back_link_para.add_run()
hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('w:anchor'), toc_bookmark_id)
hyperlink_text = OxmlElement('w:r')
rPr = OxmlElement('w:rPr')
color = OxmlElement('w:color')
color.set(qn('w:val'), '0000FF')
rPr.append(color)
u = OxmlElement('w:u')
u.set(qn('w:val'), 'single')
rPr.append(u)
hyperlink_text.append(rPr)
t = OxmlElement('w:t')
t.text = "Back to Table of Contents"
hyperlink_text.append(t)
hyperlink.append(hyperlink_text)
back_link_run._r.append(hyperlink)
# Add page break only if not the last record
if i < len(df) - 1:
page_break_para = merged_doc.add_paragraph()
run = page_break_para.add_run()
br = OxmlElement('w:br')
br.set(qn('w:type'), 'page')
run._r.append(br)
# Add page numbers to footer
section = merged_doc.sections[0]
footer = section.footer
footer_paragraph = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
footer_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
page_run = footer_paragraph.add_run()
fldChar1 = OxmlElement('w:fldChar')
fldChar1.set(qn('w:fldCharType'), 'begin')
instrText = OxmlElement('w:instrText')
instrText.text = 'PAGE'
fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'separate')
fldChar3 = OxmlElement('w:fldChar')
fldChar3.set(qn('w:fldCharType'), 'end')
page_run._r.append(fldChar1)
page_run._r.append(instrText)
page_run._r.append(fldChar2)
page_run._r.append(fldChar3)
# Save the result
output = io.BytesIO()
merged_doc.save(output)
output.seek(0)
st.success("✅ Merge completed!")
st.download_button("📥 Download merged Word document", output, file_name="merged_output.docx")
if st.button("Convert merged document to PDF"):
pdf_bytes = convert_docx_to_pdf(output.getvalue())
st.download_button("📥 Download merged PDF document", pdf_bytes, file_name="merged_output.pdf")
python
import streamlit as st
import pandas as pd
from docx import Document
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
import io
from docx2pdf import convert as docx2pdf_convert
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_TAB_ALIGNMENT, WD_TAB_LEADER, WD_BREAK
import tempfile
import os
import re
# Function to convert docx bytes to PDF bytes
def convert_docx_to_pdf(docx_bytes):
with tempfile.TemporaryDirectory() as tmpdir:
docx_path = os.path.join(tmpdir, "temp.docx")
pdf_path = os.path.join(tmpdir, "temp.pdf")
with open(docx_path, "wb") as f:
f.write(docx_bytes)
docx2pdf_convert(docx_path, pdf_path)
with open(pdf_path, "rb") as f:
pdf_bytes = f.read()
return pdf_bytes
st.title("📄 Word Mail Merge Application")
# Helper for file signature checking
def is_valid_docx(file):
try:
file.seek(0)
sig = file.read(4)
file.seek(0)
return sig == b'PK\x03\x04'
except Exception:
return False
# Convert any Word (.docx) file to PDF
st.subheader("Convert any Word (.docx) file to PDF")
docx_for_pdf = st.file_uploader("Upload a Word (.docx) file to convert to PDF", type=["docx"], key="pdfconvert")
if docx_for_pdf:
docx_filename = docx_for_pdf.name if hasattr(docx_for_pdf, 'name') else ''
if not docx_filename.lower().endswith('.docx'):
st.error("Please upload a valid Word (.docx) file. Upload cancelled.")
st.stop()
if not is_valid_docx(docx_for_pdf):
st.error("The uploaded file is not a valid Word (.docx) file. Upload cancelled.")
st.stop()
docx_bytes = docx_for_pdf.read()
with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as tmp_docx:
tmp_docx.write(docx_bytes)
tmp_docx_path = tmp_docx.name
try:
Document(tmp_docx_path)
except Exception:
st.error("The uploaded file cannot be opened as a Word document. Upload cancelled.")
os.remove(tmp_docx_path)
st.stop()
os.remove(tmp_docx_path)
if st.button("Convert uploaded Word file to PDF"):
try:
pdf_bytes = convert_docx_to_pdf(docx_bytes)
st.download_button("📥 Download converted PDF", pdf_bytes, file_name="converted_output.pdf")
except Exception as e:
st.error(f"Conversion failed: The uploaded file is not a usable Word document. Error: {e}")
# Upload Excel file and Word template
excel_file = st.file_uploader("Upload Excel file", type=["xlsx"])
template_file = st.file_uploader("Upload Word template file", type=["docx"])
# Process Excel file and preview data
if excel_file:
try:
df = pd.read_excel(excel_file)
except Exception as e:
st.error(f"Error reading Excel file: {e}")
st.stop()
df = df.drop(index=0).reset_index(drop=True)
cols = df.columns
cols_b_to_t = cols[1:20]
df = df.drop(columns=list(cols_b_to_t))
attachment_columns = [
("Q23 - Attachment 1 (optional) - Id", "Q23 - Attachment 1 (optional)"),
("Q24 - Attachment 2 (optional) - Id", "Q24 - Attachment 2 (optional)"),
("Q23_Id", "Q23 - Attachment 1 (optional)"),
("Q24_Id", "Q24 - Attachment 2 (optional)")
]
cols_to_drop = []
insert_instructions = []
for old_col, new_col in attachment_columns:
if old_col in df.columns:
pos = df.columns.get_loc(old_col)
df[new_col] = df[old_col].apply(lambda x: f"https://hkbuchtl.qualtrics.com/Q/File.php?F={x}" if pd.notnull(x) and str(x).strip() != '' else '')
cols_to_drop.append(old_col)
insert_instructions.append((new_col, pos))
if cols_to_drop:
df = df.drop(columns=cols_to_drop)
for new_col, pos in sorted(insert_instructions, key=lambda x: x[1]):
col = df.pop(new_col)
df.insert(pos, new_col, col)
for col in df.columns:
if pd.api.types.is_datetime64_any_dtype(df[col]):
df[col] = df[col].dt.strftime('%d %b %Y')
else:
try:
df[col] = pd.to_datetime(df[col]).dt.strftime('%d %b %Y')
except Exception:
pass
df = df.fillna("")
st.subheader("Preview of Processed Data")
st.dataframe(df)
# Process mail merge if both files are uploaded
if excel_file and template_file:
try:
template_doc = Document(template_file)
except Exception as e:
st.error(f"Error reading Word template file: {e}")
st.stop()
# Use the template as the base for the merged document to preserve section/spacing settings
merged_doc = Document(template_file)
# Remove all content from merged_doc but keep section settings
for _ in range(len(merged_doc.paragraphs)):
p = merged_doc.paragraphs[0]
p._element.getparent().remove(p._element)
for _ in range(len(merged_doc.tables)):
t = merged_doc.tables[0]
t._element.getparent().remove(t._element)
toc_entries = []
current_page = 1 # Start on page 1 (TOC)
# Add TOC title with bookmark
toc_title = merged_doc.add_paragraph()
toc_bookmark = OxmlElement('w:bookmarkStart')
toc_bookmark_id = "toc_bookmark"
toc_bookmark.set(qn('w:id'), '1')
toc_bookmark.set(qn('w:name'), toc_bookmark_id)
toc_title._p.insert(0, toc_bookmark)
toc_bookmark_end = OxmlElement('w:bookmarkEnd')
toc_bookmark_end.set(qn('w:id'), '1')
toc_title._p.append(toc_bookmark_end)
toc_title_run = toc_title.add_run("Table of Contents")
toc_title_run.bold = True
toc_title_run.font.size = Pt(16)
toc_title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Process records to collect TOC entries
bookmark_counter = 2
for i, row in df.iterrows():
record_page = current_page + 1 # Content starts after TOC
record_title = None
record_bookmark = f"record_{i+1}"
for para in template_doc.paragraphs:
is_heading = para.style.name.startswith('Heading')
heading_level = 0
if is_heading:
try:
heading_level = int(para.style.name.replace('Heading ', ''))
except ValueError:
heading_level = 1
full_text = para.text if para.text is not None else ""
for col in df.columns:
placeholder = f"{{{{{col}}}}}"
full_text = full_text.replace(placeholder, str(row[col]))
if full_text.strip():
full_text = re.sub(r'[ \t]+', ' ', full_text.strip())
else:
full_text = ""
if is_heading and full_text.strip():
if record_title is None:
record_title = full_text
heading_bookmark = record_bookmark
else:
heading_bookmark = f"heading_{bookmark_counter}"
bookmark_counter += 1
toc_entries.append((full_text, heading_level, record_page, heading_bookmark))
if record_title is None:
record_title = f"Record {i+1}" if not df.columns.empty else str(row[df.columns[0]])
if record_title not in [entry[0] for entry in toc_entries]:
toc_entries.append((record_title, 1, record_page, record_bookmark))
current_page += 1
# Generate TOC with hyperlinks
for text, level, page, bookmark in toc_entries:
toc_entry = merged_doc.add_paragraph()
toc_entry.paragraph_format.left_indent = Pt(level * 12)
hyperlink_run = toc_entry.add_run()
hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('w:anchor'), bookmark)
hyperlink_text = OxmlElement('w:r')
rPr = OxmlElement('w:rPr')
color = OxmlElement('w:color')
color.set(qn('w:val'), '0000FF')
rPr.append(color)
u = OxmlElement('w:u')
u.set(qn('w:val'), 'single')
rPr.append(u)
hyperlink_text.append(rPr)
t = OxmlElement('w:t')
t.text = text
hyperlink_text.append(t)
hyperlink.append(hyperlink_text)
hyperlink_run._r.append(hyperlink)
toc_entry.add_run("\t" + str(page))
tab_stops = toc_entry.paragraph_format.tab_stops
tab_stops.add_tab_stop(Pt(450), WD_TAB_ALIGNMENT.RIGHT, WD_TAB_LEADER.DOTS)
# Add page break after TOC using XML to ensure reliability
toc_last_para = merged_doc.add_paragraph()
run = toc_last_para.add_run()
br = OxmlElement('w:br')
br.set(qn('w:type'), 'page')
run._r.append(br)
# Add content with bookmarks and "Back to TOC" links
for i, row in df.iterrows():
record_bookmark = f"record_{i+1}"
record_added = False
for para in template_doc.paragraphs:
new_para = merged_doc.add_paragraph()
new_para.style = para.style
is_heading = para.style.name.startswith('Heading')
if not record_added:
bookmark = OxmlElement('w:bookmarkStart')
bookmark.set(qn('w:id'), str(i + 2))
bookmark.set(qn('w:name'), record_bookmark)
new_para._p.insert(0, bookmark)
bookmark_end = OxmlElement('w:bookmarkEnd')
bookmark_end.set(qn('w:id'), str(i + 2))
new_para._p.append(bookmark_end)
record_added = True
full_text = para.text if para.text is not None else ""
for col in df.columns:
placeholder = f"{{{{{col}}}}}"
value = str(row[col])
# Preserve line breaks in the value
value = value.replace('\r\n', '\n').replace('\r', '\n')
full_text = full_text.replace(placeholder, value)
if full_text.strip():
# Remove only extra spaces/tabs, but preserve line breaks
full_text = re.sub(r'[ \t]+', ' ', full_text)
lines = full_text.split('\n')
else:
lines = []
if lines:
while new_para.runs:
new_para.runs[0]._element.getparent().remove(new_para.runs[0]._element)
if para.runs:
run = para.runs[0]
for idx, line in enumerate(lines):
new_run = new_para.add_run(line.strip())
new_run.bold = run.bold
new_run.italic = run.italic
new_run.underline = run.underline
new_run.font.color.rgb = run.font.color.rgb
new_run.font.size = run.font.size
new_run.font.name = run.font.name
new_run.font.highlight_color = run.font.highlight_color
new_run.font.superscript = run.font.superscript
new_run.font.subscript = run.font.subscript
if idx < len(lines) - 1:
new_run.add_break(WD_BREAK.LINE)
else:
for idx, line in enumerate(lines):
run = new_para.add_run(line.strip())
if idx < len(lines) - 1:
run.add_break(WD_BREAK.LINE)
new_para.alignment = para.alignment
else:
new_para._element.getparent().remove(new_para._element)
# Add "Back to TOC" link
back_link_para = merged_doc.add_paragraph()
back_link_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
back_link_run = back_link_para.add_run()
hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('w:anchor'), toc_bookmark_id)
hyperlink_text = OxmlElement('w:r')
rPr = OxmlElement('w:rPr')
color = OxmlElement('w:color')
color.set(qn('w:val'), '0000FF')
rPr.append(color)
u = OxmlElement('w:u')
u.set(qn('w:val'), 'single')
rPr.append(u)
hyperlink_text.append(rPr)
t = OxmlElement('w:t')
t.text = "Back to Table of Contents"
hyperlink_text.append(t)
hyperlink.append(hyperlink_text)
back_link_run._r.append(hyperlink)
# Add page break only if not the last record
if i < len(df) - 1:
page_break_para = merged_doc.add_paragraph()
run = page_break_para.add_run()
br = OxmlElement('w:br')
br.set(qn('w:type'), 'page')
run._r.append(br)
# Add page numbers to footer
section = merged_doc.sections[0]
footer = section.footer
footer_paragraph = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
footer_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
page_run = footer_paragraph.add_run()
fldChar1 = OxmlElement('w:fldChar')
fldChar1.set(qn('w:fldCharType'), 'begin')
instrText = OxmlElement('w:instrText')
instrText.text = 'PAGE'
fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'separate')
fldChar3 = OxmlElement('w:fldChar')
fldChar3.set(qn('w:fldCharType'), 'end')
page_run._r.append(fldChar1)
page_run._r.append(instrText)
page_run._r.append(fldChar2)
page_run._r.append(fldChar3)
# Save the result
output = io.BytesIO()
merged_doc.save(output)
output.seek(0)
st.success("✅ Merge completed!")
st.download_button("📥 Download merged Word document", output, file_name="merged_output.docx")
if st.button("Convert merged document to PDF"):
pdf_bytes = convert_docx_to_pdf(output.getvalue())
st.download_button("📥 Download merged PDF document", pdf_bytes, file_name="merged_output.pdf")
Would you like me to explain or break down this code?