I’m trying to create a new document from multiple existing documents and I think I am doing it wrong.
I started with a huge document containing multiple chapters and subchapters (not sections). Then I splitted this document in single chapters and subchapters. Each chapter and subchapter is stored in a single file (docx). I did this by deleting all other chapters form the main document and then saving the rest. So I have an array of multiple files all with the same styles.
Then I use a simple construct in vb.net to iterate through these documents and combine them to a singe document.
Dim targetfile = DocumentModel.load("firstChapter.docx")
For i = 2 To UBound(ArrayOfFiles)- 1
Dim Source = DocumentModel.Load(ArrayOfFiles(i))
targetfile.Content.End.InsertRange(Source.Content)
Next
targetfile.Save("someName.docx")
On the first glance every thing is fine and lightnig fast (compared to native VBA).
But,
when opening “someName.docx” behind every document, added by “content.end.insert” there is a new (floating) section.
there are plenty of new styles (heading 1_1, heading 1_2, heading 1_3 etc.) and from the second imported document on, the heading styles are not numbered any more.
Is there any way to
insert a new document to an existing document without creating a new section
You can avoid the creation of a new section by importing the content of those source documents block by block.
Also, you can avoid the creation of duplicate styles by specifying that the destination style should be used. However, doing just that won’t be enough for list styles, those will have to be explicitly mapped.
So in short, try something like this:
Does it solve your issue?
Dim files As String() = {"Chapter1.docx", "Chapter2.docx", "Chapter3.docx"}
Dim destination = DocumentModel.Load(files(0))
Dim destinationSection = destination.Sections.Last()
For i As Integer = 1 To files.Length - 1
Dim source = DocumentModel.Load(files(i))
Dim mapping = New ImportMapping(source, destination, useDestinationStyles:=True)
' This is usually not needed, specifying the "useDestinationStyles" to "true" is enough for most cases.
' But list styles have special handling, they are always imported as a new style.
For Each style In source.Styles
mapping.SetDestinationStyle(style, destination.Styles(style.Name))
Next
' I believe that your source documents have only one section so this should be fine.
' However, in case I am wrong then you can do this for the first section, and for others import them to "document.Sections".
For Each sourceBlock In source.Sections(0).Blocks
Dim destinationBlock = destination.Import(sourceBlock, True, mapping)
destinationSection.Blocks.Add(destinationBlock)
Next
Next
destination.Save("Chapters.docx")