Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Fri Oct 10, 2025 2:00 pm

I am trying to merge multiple docx to a single docx . But in this process the page numbers get auto incremented.
I need to maintain the page numbers from the original docx such that no auto increment happens in the merged doc. I use Spire.Doc to merge the docx files.

Spire.doc version - 13.8.0

santhosha
 
Posts: 4
Joined: Fri Oct 10, 2025 1:41 pm

Sat Oct 11, 2025 2:12 am

Hello,

Thank you for your inquiry.
To merge the files while preserving the original page numbers of the documents, please refer to the following code using the latest version of Spire.Doc for .NET 13.9.10:
Code: Select all
            Document document = new Document();
            document.LoadFromFile(@"Test1.docx");
            Document document1 = new Document();
            document1.LoadFromFile(@"Test2.docx");

            for (int i = document1.Sections.Count - 1; i >= 0; i--)
            {
                Section section = document1.Sections[i];
                document.Sections.Insert(0, section.Clone());
            }

            for (int i = 0; i < document.Sections.Count; i++)
            {
                Section section = document.Sections[i];
                HeaderFooter footer = section.HeadersFooters.Footer;
                if (footer.Paragraphs.Count <= 0) continue;
                Paragraph paragraph = footer.Paragraphs[0];
                foreach (DocumentObject documentObject in paragraph.ChildObjects)
                {
                    if (documentObject.DocumentObjectType == DocumentObjectType.Field)
                    {
                        Field field = (Field)documentObject;
                        if (field.Type == FieldType.FieldNumPages)
                        {
                            field.Type = FieldType.FieldSectionPages;
                        }
                    }
                }
                section.PageSetup.RestartPageNumbering = true;
                section.PageSetup.PageStartingNumber = 1;
            }

            document.SaveToFile(@"result.docx", FileFormat.Docx);


If the above code does not meet your requirements, please send us the files you used for testing, and we will conduct further investigation. You may upload the files as attachments or send them directly to my email: [email protected]. We look forward to your feedback.
Sincerely,
Talia
E-iceblue support team
User avatar

talia.liu
 
Posts: 341
Joined: Mon Apr 14, 2025 3:33 am

Mon Oct 13, 2025 7:10 am

Hi

Thank you for your response.

We use Spire.doc for Python. Please find the code snippet below for further reference.

Code: Select all

merged_doc = None

for root, dirs, files in os.walk(documents_path):
   for file in files:
      filename, extension = os.path.splitext(file)
      if extension in ['.docx','.doc']:
         doc_file_path = os.path.join(root,file)
         
         source_doc = Document()
         source_doc.LoadFromFile(doc_file_path)
         source_doc.KeepSameFormat = True


         if merged_doc is None:
            merged_doc = source_doc
         else:
            # merged_doc.ImportContent(source_doc)
            # # print(dir(merged_doc))


            for sec_content in range(source_doc.Sections.Count):
               section = source_doc.Sections.get_Item(sec_content)
               cloneSection = section.Clone()
               cloneSection.HeadersFooters.LinkToPrevious = False
               cloneSection.PageSetup.RestartPageNumbering = True
               cloneSection.PageSetup.PageStartingNumber = 1
               merged_doc.Sections.Add(cloneSection)
 

merged_doc.SaveToFile("MergeDocument.docx", FileFormat.Docx2019)
merged_doc.Close()
source_doc.Close()


santhosha
 
Posts: 4
Joined: Fri Oct 10, 2025 1:41 pm

Mon Oct 13, 2025 8:42 am

Hello,

Thank you for your feedback.
please refer to the following code:
Code: Select all
import os
from spire.doc import FileFormat, Document, DocumentObjectType, FieldType

merged_doc = None

for root, dirs, files in os.walk(doc_path):
    for file in files:
        filename, extension = os.path.splitext(file)
        if extension in ['.docx', '.doc']:
            doc_file_path = os.path.join(root, file)

            source_doc = Document()
            source_doc.LoadFromFile(doc_file_path)
            source_doc.KeepSameFormat = True

            if merged_doc is None:
                merged_doc = source_doc
            else:
                for i in range(source_doc.Sections.Count - 1, -1, -1):
                    section = source_doc.Sections.get_Item(i)
                    merged_doc.Sections.Insert(0, section.Clone())

for i in range(merged_doc.Sections.Count):
    section = merged_doc.Sections.get_Item(i)
    footer = section.HeadersFooters.Footer
    if footer.Paragraphs.Count <= 0:
        continue
    paragraph = footer.Paragraphs[0]
    for j in range(paragraph.ChildObjects.Count):
        documentObject = paragraph.ChildObjects[j]
        if documentObject.DocumentObjectType == DocumentObjectType.Field:
            field = documentObject
            if field.Type == FieldType.FieldNumPages:
                field.Type = FieldType.FieldSectionPages
    section.PageSetup.RestartPageNumbering = True
    section.PageSetup.PageStartingNumber = 1

merged_doc.SaveToFile(r"result.docx", FileFormat.Docx)
merged_doc.Close()


If the above code does not meet your requirements, please send us the files you used for testing, and we will conduct further investigation. We are looking forward to your feedback.
Sincerely,
Talia
E-iceblue support team
User avatar

talia.liu
 
Posts: 341
Joined: Mon Apr 14, 2025 3:33 am

Mon Oct 13, 2025 10:18 am

The merging functionality is working fine now. However, we have encountered one more issue.

Consider two DOCX files:

The first document has 3 pages

The second document has 2 pages

When we merge these two documents, the page numbering in the merged output shows as 1 of 5, 2 of 5, and so on.
What we actually need is:

For the first document: 1 of 3, 2 of 3, 3 of 3

For the second document: 1 of 2, 2 of 2

In other words, each document’s page numbering should remain relative to its own total page count, not the combined total after merging.

Please let us know how we can achieve this using Spire.Doc for Python.

santhosha
 
Posts: 4
Joined: Fri Oct 10, 2025 1:41 pm

Tue Oct 14, 2025 7:44 am

Hello,

Thank you for your feedback.
Please refer to the following code:
Code: Select all
merged_doc = None
for root, dirs, files in os.walk(R"....\test"):
    for file in files:
        filename, extension = os.path.splitext(file)
        if extension in ['.docx', '.doc']:
            doc_file_path = os.path.join(root, file)

            source_doc = Document()
            source_doc.LoadFromFile(doc_file_path)
            source_doc.KeepSameFormat = True

            allpages=0
            if merged_doc is None:
                merged_doc = source_doc
                allpages = merged_doc.GetPageCount()
                print(allpages)
            else:
                allpages = source_doc.GetPageCount()
                print(allpages)
                for i in range(source_doc.Sections.Count - 1, -1, -1):
                    section = source_doc.Sections.get_Item(i)
                    merged_doc.Sections.Insert(0, section.Clone())


for i in range(merged_doc.Sections.Count):
    section = merged_doc.Sections.get_Item(i)
    footer = section.HeadersFooters.Footer
    if footer.Paragraphs.Count <= 0:
        continue
    paragraph = footer.Paragraphs[0]
    for j in range(paragraph.ChildObjects.Count):
        documentObject = paragraph.ChildObjects[j]
        if documentObject.DocumentObjectType == DocumentObjectType.Field:
            field = documentObject
            if field.Type == FieldType.FieldNumPages:
                field.Type = FieldType.FieldSectionPages
    section.PageSetup.RestartPageNumbering = True
    section.PageSetup.PageStartingNumber = 1
    paragraph.AppendField("page number", FieldType.FieldPage)
    paragraph.AppendText(" of ")
    paragraph.AppendField("number of pages", FieldType.FieldSectionPages)


merged_doc.SaveToFile(R"result.docx", FileFormat.Docx)
merged_doc.Close()
Sincerely,
Talia
E-iceblue support team
User avatar

talia.liu
 
Posts: 341
Joined: Mon Apr 14, 2025 3:33 am

Mon Oct 27, 2025 10:00 pm

We tried the suggested solution, but unfortunately the page numbering still isn’t working as expected. Even after applying the section-based numbering logic, each merged document is showing a continuous total (e.g., 1 of 5) instead of restarting numbering per section (1 of 3, 1 of 2, etc.).

We’ve attached the two sample source files along with the merged output for your reference. Could you please review and let us know what might be causing this issue?

santhosha
 
Posts: 4
Joined: Fri Oct 10, 2025 1:41 pm

Tue Oct 28, 2025 2:21 am

Hello,

Thank you for your feedback.
When I opened your result file, the output appeared as shown in the screenshot below. Could you please tell us whether you are seeing the same result in your environment?
result.png

To address this issue, I have adjusted the code accordingly. Please refer to the following code. In my local environment, the result file now displays as shown in the subsequent screenshot. I have also attached my result file for your reference.
Code: Select all
import os
from spire.doc import FileFormat, Document, DocumentObjectType, FieldType

merged_doc = None
for root, dirs, files in os.walk(R"...\test"):
    for file in files:
        filename, extension = os.path.splitext(file)
        if extension in ['.docx', '.doc']:
            doc_file_path = os.path.join(root, file)

            source_doc = Document()
            source_doc.LoadFromFile(doc_file_path)
            source_doc.KeepSameFormat = True

            allpages=0
            if merged_doc is None:
                merged_doc = source_doc
                allpages = merged_doc.GetPageCount()
                print(allpages)
            else:
                allpages = source_doc.GetPageCount()
                print(allpages)
                for i in range(source_doc.Sections.Count - 1, -1, -1):
                    section = source_doc.Sections.get_Item(i)
                    merged_doc.Sections.Insert(0, section.Clone())


for i in range(merged_doc.Sections.Count):
    section = merged_doc.Sections.get_Item(i)
    footer = section.HeadersFooters.Footer
    if footer is not None:
        footer.ChildObjects.Clear()
    section.PageSetup.RestartPageNumbering = True
    section.PageSetup.PageStartingNumber = 1
    footerParagraph = footer.AddParagraph()
    footerParagraph.AppendField("page number", FieldType.FieldPage)
    footerParagraph.AppendText("/")
    footerParagraph.AppendField("number of pages", FieldType.FieldSectionPages)

merged_doc.SaveToFile(R"testresult.docx", FileFormat.Docx)
merged_doc.Close()

testresult.png

We look forward to your feedback.
Sincerely,
Talia
E-iceblue support team
User avatar

talia.liu
 
Posts: 341
Joined: Mon Apr 14, 2025 3:33 am

Return to Spire.Doc