Commit a09a45d3 authored by Miguel Angel Reina Ortega's avatar Miguel Angel Reina Ortega
Browse files

Adding List of Figures/Tables

parent a70bb3f8
Loading
Loading
Loading
Loading
Loading
+52 −0
Original line number Diff line number Diff line
@@ -462,6 +462,58 @@ def update_toc(docx_input, docx_output):
        if os.path.exists(tmp_path):
            os.remove(tmp_path)

def update_lof_to_loft(xml_data, ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}):
    root = etree.fromstring(xml_data)
    loft_switch = '\\t "TH,1" \\c "Figure" '
    # Match full LOF caption switch with flexible spacing.
    pattern = re.compile(r'\\c\s*"Figure"\s*')

    # Track TOC paragraphs to insert page break after
    toc_paragraphs = []

    # Loop over all elements to find "TOC"
    for elem in root.xpath('.//w:instrText', namespaces=ns):
        if 'TOC' in elem.text:
            old_text = elem.text
            # Replace full \c "Figure" switch by \t "TH,1" \c "Figure"
            # and keep operation idempotent.
            if '\\t "TH,1"' not in elem.text:
                elem.text = pattern.sub(loft_switch, elem.text)
            if elem.text != old_text:
                print(f'Changed LOF: {old_text}{elem.text}')
            
            # Find the paragraph containing this TOC field
            toc_para = elem
            while toc_para is not None and toc_para.tag != f"{{{ns['w']}}}p":
                toc_para = toc_para.getparent()
            
            if toc_para is not None and toc_para not in toc_paragraphs:
                toc_paragraphs.append(toc_para)
    
    # Insert page break after each TOC paragraph
    for toc_para in toc_paragraphs:
        parent = toc_para.getparent()
        if parent is None:
            continue
        
        # Find the position of the TOC paragraph
        para_index = list(parent).index(toc_para)
        
        # Create a new paragraph with a page break
        page_break_para = OxmlElement('w:p')
        page_break_run = OxmlElement('w:r')
        page_break = OxmlElement('w:br')
        page_break.set(f"{{{ns['w']}}}type", "page")
        page_break_run.append(page_break)
        page_break_para.append(page_break_run)
        
        # Insert the page break paragraph after the TOC paragraph
        parent.insert(para_index + 1, page_break_para)
        print(f'Inserted page break after TOC')

    return etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes")


#def update_toc_level(config):
#    docx_path = config.get("output_docx")
#    word = win32com.client.Dispatch("Word.Application")