Edit content in header of document Python-docx

Viewed 3193

I am trying to find and replace text in a Textbox in Header of document. But after searching for awhile, it seems there is no way to access the content in the Header or "float" text boxes via python-docx (I read issue here)

So, it means we have to find and replace directly on the xml format of document. Do you know anyway to do that?

2 Answers

Another way to do this, in memory:

def docx_setup_header(doc_sio_1, new_title):
    """
    Returns a StringIO having replaced #TITLE# placeholder in document header with new_title
    :param doc_sio_1:  A StringIO instance of the docx document.
    :param new_title:  The new title to be inserted into header, replacing #TITLE# placeholder
    :return: A new StringIO instance, with modified document.
    """

    HEADER_PATH = 'word/header1.xml'

    doc_zip_1 = zipfile.ZipFile(doc_sio_1, 'r')
    header = doc_zip_1.read(HEADER_PATH)
    header = header.replace("#TITLE#", new_title)

    doc_sio_2 = StringIO.StringIO()
    doc_zip_2 = zipfile.ZipFile(doc_sio_2, 'w')
    for item in doc_zip_1.infolist():
        content = doc_zip_1.read(item.filename)
        if item.filename == HEADER_PATH:
            doc_zip_2.writestr(HEADER_PATH, header, zipfile.ZIP_DEFLATED)
        else:
            doc_zip_2.writestr(item, content)

    doc_zip_1.close()
    doc_zip_2.close()

    return doc_sio_2

Note that Python's zipfile cannot replace or delete items, so you need to make up a brand new zipfile, and copy unchanged elements from original.

Related