I need to remove headers and footers in many docx files. I was currently trying using python-docx library, but it doesn't support header and footer in docx document at this time (work in progress).
Is there any way to achieve that in Python?
As I understand, docx is a xml-based format, but I don't know how to use it.
P.S.I have an idea to use lxml or BeautifulSoup to parse xml and replace some parts, but it looks dirty
UPD. Thanks to Shawn, for a good start point. I was made some changes to script. This is my final version (it's usefull for me, because I need to edit many .docx files. I'm using BeautifulSoup, because standart xml parser can't get a valid xml-tree. Also, my docx documents doesn't have header and footer in xml. They just placed the header's and footer's images in a top of page. Also, for more speed you can use lxml instead of Soup.
import zipfile
import shutil as su
import os
import tempfile
from bs4 import BeautifulSoup
def get_xml_from_docx(docx_filename):
"""
Return content of document.xml file inside docx document
"""
with zipfile.ZipFile(docx_filename) as zf:
xml_info = zf.read('word/document.xml')
return xml_info
def write_and_close_docx(self, edited_xml, output_filename):
""" Create a temp directory, expand the original docx zip.
Write the modified xml to word/document.xml
Zip it up as the new docx
"""
tmp_dir = tempfile.mkdtemp()
with zipfile.ZipFile(self) as zf:
zf.extractall(tmp_dir)
with open(os.path.join(tmp_dir, 'word/document.xml'), 'w') as f:
f.write(str(edited_xml))
# Get a list of all the files in the original docx zipfile
filenames = zf.namelist()
# Now, create the new zip file and add all the filex into the archive
zip_copy_filename = output_filename
docx = zipfile.ZipFile(zip_copy_filename, "w")
for filename in filenames:
docx.write(os.path.join(tmp_dir, filename), filename)
# Clean up the temp dir
su.rmtree(tmp_dir)
if __name__ == '__main__':
directory = 'your_directory/'
files = os.listdir(directory)
for file in files:
if file.endswith('.docx'):
word_doc = directory + file
new_word_doc = 'edited/' + file.rstrip('.docx') + '-edited.docx'
tree = get_xml_from_docx(word_doc)
soup = BeautifulSoup(tree, 'xml')
shapes = soup.find_all('shape')
for shape in shapes:
if 'margin-left:0pt' in shape.get('style'):
shape.parent.decompose()
write_and_close_docx(word_doc, soup, new_word_doc)
So, that's it :) I know, the code isn't clean, sorry for that.