Free Support Forum - aspose.com

MERGE 2 Word Docs Into One Plus Auto Create TOC

Hi
I have Aspose Word v11.8 (part of Aspose Total .NET) my company just bought.

I want to do the following.

Doc1.doc - this has only 1 line of text that is the title of a paragraph.
Doc2.doc - This is the paragraph of text
final.doc - this is the doc1.doc + doc2.doc merged with an auto created TOC on the first page.

I have tried but i just cannot get it to work. I cannot get the doc1.doc which is the paragraph title text to have the Heading Style 1 applied on it.

I have attached all 3 documents.

Hi Nitin,


Thanks for your inquiry. You first need to import the Title of the Paragraph from source document to destination document. Once done, you can they format it with a Heading 1 style and then insert TOC at the start of document by using the code like below:

Document srcDoc = new
Document(@“C:\Temp\Doc1.doc”);

Document dstDoc = new Document(@"C:\Temp\Doc2.doc");

DocumentBuilder dstBuilder = new DocumentBuilder(dstDoc);

Paragraph dstNode = (Paragraph)dstDoc.ImportNode(srcDoc.FirstSection.Body.FirstParagraph, true);

dstNode.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

dstDoc.FirstSection.Body.Paragraphs.Insert(0, dstNode);

dstBuilder.MoveToDocumentStart();

dstBuilder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");

dstBuilder.InsertBreak(BreakType.PageBreak);

dstDoc.UpdateFields();

dstDoc.Save(@"C:\Temp\out.doc");


I hope, this helps.

Best Regards,

Hi there...

Thanks for the code... however I have THREE documents.

Doc1.doc = this has only 1 line of text that is the title of a paragraph.
Doc2.doc = This is the Normal paragraph of text
final.doc = this is the doc1.doc + doc2.doc merged with an auto created TOC on the first page.

Please see the 3 attached documents (on the first message in this thread) for what i want to acheive.

Hi Nitin,


Thanks for your inquiry. I believe, the code mentioned in my previous post achieves what you’re looking for (See the output produced in out.doc). Please try running it with Aspose.Words version 11.9.0. I hope, this helps.

Best Regards,

This code works well - thank you.
Just one more thing.
my final document has empty pages (page breaks) and blank lines.

How can I remove all blank lines and empty page breaks.

Hi Nitin,


Thanks for your inquiry. Sure, please try using the following code snippet:

//get last section

Section lastSect = doc.LastSection;

// Remove page break from the last pagagraph of the document

foreach (Run run in lastSect.Body.LastParagraph.Runs)

run.Text = run.Text.Replace(ControlChar.PageBreak, " ");

//Remove empty paragraphs from the end of the document

while (string.IsNullOrEmpty(lastSect.Body.LastParagraph.ToString(SaveFormat.Text).Trim()))

{

lastSect.Body.LastParagraph.Remove();

}

I hope, this helps.

Best Regards,