We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Combine Word documents within a paragraph

We have a need to insert small Word documents (we call them document parts or boilerplate text) into a larger word document (we call these templates).
The first requirement for this is that the formatting from the boilerplate word documents must be maintained when inserted into the template document. We have gotten this to work through the document builder.InsertDocument method.
The second requirement for this is that the insertion point is that the document part does not have to be it’s own paragraph, rather it can be inserted directly into an existing paragraph or even a sentence without adding line breaks, paragraph breaks or section breaks.

So far all of our attempts to combine these document parts into an existing paragraph results in a new line being generated within the template at the point of insertion.

So my question is - Is it possible to use Aspose.Words to insert a word document into another word document without a line break, paragraph break or section break?

For example:
This is the template document and we’d like to insert formatted text here, without generating a new line.

The above is showing up as:
This is the template document that we’d like to insert formatted text here
this is the inserted text as you can see it is on a new line, without generating a new line.

We need it to show up as:
This is the template document that we’d like to insert formatted text here this is the inserted text as you can see it is on a new line, without generating a new line.

Thanks,
Paul

@Paul.D.McDonald,

Please see the sample documents in Docs.zip (26.4 KB) and try running the following code:

Document docTemplate = new Document(MyDir + @"template.docx");
Document docPart = new Document(MyDir + @"part.docx");

// Insert document at Bookmark's position
DocumentBuilder builder = new DocumentBuilder(docTemplate);
builder.MoveToBookmark("bm", false, true);
builder.InsertDocument(docPart, ImportFormatMode.KeepSourceFormatting);
// Remove Bookmark
docTemplate.Range.Bookmarks["bm"].Text = "";
docTemplate.Range.Bookmarks["bm"].Remove();
// Copy all child nodes of current Paragraph to the end of previous Paragraph
Paragraph prevPara = (Paragraph)builder.CurrentParagraph.PreviousSibling;
foreach (Node node in builder.CurrentParagraph.ChildNodes)
{
    prevPara.AppendChild(node.Clone(true));
}
// Remove copied nodes
builder.CurrentParagraph.RemoveAllChildren();

docTemplate.Save(MyDir + @"18.2.docx");

Thank you very much Awais.

This was quite helpful. The code works well.

Paul

Hello, we have been using a variation of this code now for a few months and just noticed that when replacing a merge field that is within an IF statement, it adds a leading space to the contents of the document that is being inserted into the main document.

I can send you a working C# application that illustrates the leading space that is being inserted. The second paragraph within the resulting merged document has a space at the beginning of the paragraph.

Below is the code from the solution.

Please take a look and advise on how we can remove the leading space.

Thank you,
Paul

using Aspose.Words;
using System;
using System.Data;

namespace AsposeInsertDocumentHasLeadingSpace
{
class Program
{
static void Main(string[] args)
{
SetLicense();

        string mainDocPath = Environment.CurrentDirectory + @"\MainDocument.docx";
        string ResultPreMergeDocPath = Environment.CurrentDirectory + @"\MergeResultPreMerge.docx";
        string ResultPostMergeDocPath = Environment.CurrentDirectory + @"\MergeResultPostMerge.docx";
        string tanfDocPath = Environment.CurrentDirectory + @"\MERGE-TANF-LINE.docx";
        string naDocPath = Environment.CurrentDirectory + @"\MERGE-NA-LINE.docx";

        Document mainDoc = new Document(mainDocPath);

        //replace TANF merge field with contents from document
        ReplaceMergeFieldWithDocument(mainDoc, "MERGE-TANF-LINE", tanfDocPath);

        //replace TANF merge field with contents from document
        ReplaceMergeFieldWithDocument(mainDoc, "MERGE-NA-LINE", naDocPath);

        //save document after replacing documents and before doing a mail merge
        mainDoc.Save(ResultPreMergeDocPath);

        //create a datatable with 2 records and do the mail merge
        using (var dt = new DataTable("TANF"))
        {
            dt.Columns.Add(new DataColumn("WS-TANF-IND"));
            dt.Rows.Add("Y");
            dt.Rows.Add("N");
            mainDoc.MailMerge.Execute(dt);
        }

        //save document after replacing documents and after doing a mail merge
        mainDoc.Save(ResultPostMergeDocPath);

    }

    public static void ReplaceMergeFieldWithDocument(Document doc, string mergeFieldName, string insertFilePath)
    {
        //create document builder for main document.
        var builder = new DocumentBuilder(doc);

        //move to the merge field to replace
        builder.MoveToMergeField(mergeFieldName, false, true);

        //load the sub-document which will replace the merge field.
        var subDoc = new Document(insertFilePath);

        //insert the Word sub-document in place of the merge field
        builder.InsertDocument(subDoc, ImportFormatMode.KeepSourceFormatting);

        // Copy all child nodes of current Paragraph to the end of previous Paragraph
        Paragraph prevPara = (Paragraph)builder.CurrentParagraph.PreviousSibling;
        foreach (Node node in builder.CurrentParagraph.ChildNodes)
        {
            prevPara.AppendChild(node.Clone(true));
        }

        // Remove copied nodes
        builder.CurrentParagraph.RemoveAllChildren();

        //Remove empty paragraph.
        if (((Paragraph)prevPara.NextSibling).ChildNodes.Count == 0)
        {
            prevPara.NextSibling.Remove();
        }
    }

    private static void SetLicense()
    {
        var WordLicense = new License();
        WordLicense.SetLicense("Aspose.Total.lic");
    }
}

}

@Paul.D.McDonald,

Please create a standalone simple console application (source code without compilation errors) that helps us to reproduce your problem on our end and attach it here for testing. Also, please provide related input/output Word documents to reproduce the same issue on our end. Thanks for your cooperation.

AsposeInsertDocumentHasLeadingSpace.zip (53.8 KB)

Please see attached. Thanks.

@Paul.D.McDonald,

Thanks for the additional information. Simple code to reproduce this issue is as follows:

Document doc = new Document("D:\\temp\\MainDocument.docx");
Document doc1 = new Document("D:\\temp\\MERGE-TANF-LINE.docx");
Document doc2 = new Document("D:\\temp\\MERGE-NA-LINE.docx");

DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToMergeField("MERGE-TANF-LINE", false, true);
builder.InsertDocument(doc1, ImportFormatMode.KeepSourceFormatting);

builder.MoveToMergeField("MERGE-NA-LINE", false, true);
builder.InsertDocument(doc2, ImportFormatMode.KeepSourceFormatting);

using (var dt = new DataTable("TANF"))
{
    dt.Columns.Add(new DataColumn("WS-TANF-IND"));
    dt.Rows.Add("Y");
    dt.Rows.Add("N");
    doc.MailMerge.Execute(dt);
}

doc.Save("D:\\Temp\\18.6.docx"); 

We tested the scenario and have managed to reproduce the same problem on our end. For the sake of correction, we have logged this problem in our issue tracking system. The ID of this issue is WORDSNET-17083. We will further look into the details of this problem and will keep you updated on the status of correction. We apologize for your inconvenience.

Thank you, Awais.

Hello, I wanted to check in with the Aspose team to see if this issue can be moved up the priority list.

A long term project that we are currently working on is nearing production and this issue is blocking our path forward to moving the application into production.

Thank you and I look forward to your response.
Paul

@Paul.D.McDonald,

Unfortunately, this issue is not resolved yet. We have logged your concerns in our issue tracking system. We will keep you posted on further updates and apologize for any inconvenience.

Awais, what are our options to move this up on your teams priority list?

Thanks,
Paul

@Paul.D.McDonald,

If this issue is important to you, and for the fast resolution of this issue, please have a look at the paid support options - e.g. purchasing ‘Paid Support’ will allow you to post your issues in our Paid Support Helpdesk and raise the priority of this issue. Many ‘Paid Support’ customers find that this leads to their issues being fixed in the next release of the software.

If you would like to take advantage of the ‘Paid Support’ then please request a quote in our purchase forum - https://forum.aspose.com/c/purchase

We apologize for any inconvenience and thank you for your understanding.

The issues you have found earlier (filed as WORDSNET-17083) have been fixed in this Aspose.Words for .NET 19.4 update and this Aspose.Words for Java 19.4 update.