I have a bunch of existing documents. Problem: they have no title. My idea is to open every document and add the (modified) filename as a title.
I can't find a way to insert a title at the beginning of an existing document. Every command i tried adds the title at the end of the document.
I hope one of you can give me a hint which command and how I can use it.
You can achieve this by using the insert_paragraph_before
method and inserting the title before the first paragraph:
from docx import Document
def insert_title(docx_file, title):
document = Document(docx_file)
# Insert the title at the beginning
document.paragraphs[0].insert_paragraph_before(title, style='Heading 1')
document.save(docx_file)
Then you can easily add a title like this:
insert_title('my_document.docx', "Hello, World!")
If you want to add a page break after the title (to have it on a separate page):
from docx.enum.text import WD_BREAK
from docx import Document
def insert_title(docx_file, title):
document = Document(docx_file)
# Insert the title at the beginning
heading = document.paragraphs[0].insert_paragraph_before(title, style='Heading 1')
run = heading.add_run()
run.add_break(WD_BREAK.PAGE)
document.save(docx_file)