Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Word files with python-docx and add page breaks

I'm trying to combine few Word files in one with python-docx, and separate them inside with page breaks. Each file contains arbitrary elements. I made 3 test files for example, each of them consist 1 paragraph - "Test 1" (2, 3). Here is my code:

from docx import Document

docs = []
docsTitles.append('test/Test1.docx')
docsTitles.append('test/Test2.docx')
docsTitles.append('test/Test3.docx')
i = 0
for item in docsTitles:
    docs.append(Document(item))
    if (i != 0):
        docs[0].add_page_break()
        for element in docs[i].element.body:
            docs[0].element.body.append(element)
    i = i + 1
docs[0].save('test/testReport.docx')

But testReport.docx turns out like this:

Test 1

page break

page break

Test 2

Test 3

instead of

Test 1

page break

Test 2

page break

Test 3

What am I doing wrong?

like image 497
Julia Avatar asked Sep 01 '25 04:09

Julia


1 Answers

The problem is here:

Instead of docs[0].add_page_break(), it should be docs[i].add_page_break()

like image 81
Mayank Porwal Avatar answered Sep 02 '25 18:09

Mayank Porwal