Sample vb code using COM/CreateObject() command for inserting a document

Hi,

I am currently testing this software for use and cannot figure out how to insert one document into another documents bookmark using vb code via COM and cannot find any good samples that show the code needed for CreateObject().

Can you provide me with some sample code using CreateObject showing how to insert a document into a bookmark of another in either vb or asp?

Thanks!!!

Hi

Thanks for your inquiry. I think that the best method to do this is creating wrapper class. For more information please refer the following links.
https://docs.aspose.com/words/net/supported-platforms/#com

I hope this could help you.

Best regards.

I am trying to create the wrapper. When I try to build what I have I get this error message: ‘AsposeComWrapper.Methods.InsertDocument(Aspose.Words.Note, Aspose.Words.Document)’: not all code paths return a value.

My code is attached.

Please advise.

Thanks!

Hi again.

This error, “not all code paths return a value” shows up when you are writing a function declared with some return type and forget return statement. If you function has conditional branches then you need to ensure that every branch leads to some return statement.

Have a nice day,

Thank you for the information you provided!

I am stuck!

I created the dll and registered it according to the insructions.

When I try and run from Excel button I get an error stating: Wrong number of arguments or invalid propery assignment. (Run-time error ‘450’).

Here is my code from Excel, can you tell me what I’m doing wrong here?

Thanks!!!

Private Sub CommandButton1\_Click()
Dim subDoc As Object, Helper As Object, Wrapper As Object, mainDoc As Object
Set Helper = CreateObject("Aspose.Words.ComHelper")
Set mainDoc = Helper.Open("c:\testdata\ProductSOSTemp1.doc")
Set subDoc = Helper.Open("c:\testdata\1SOS1.DOC")
Set Wrapper = CreateObject("AsposeComWrapper.Methods")
Wrapper.InsertDocument mainDoc.Range.Bookmarks("ProductSOSInsert").BookmarkStart.ParentNode, subDoc
Set Wrapper = Nothing
Set subDoc = Nothing
Set mainDoc = Nothing
Set Helper = Nothing
End Sub

Hi

Thanks fro additional information. Please try using the following method in your Wrapper class.

public void InsertDocument(object afterNode, object doc)
{
    Document srcDoc;
    Node insertAfterNode;
    try
    {
        srcDoc = (Document)doc;
        insertAfterNode = (Node)afterNode;
    }
    catch
    {
        throw new ArgumentException("Invalid arguments");
    }

    // We need to make sure that the specified node is either pargraph or table.
    if (!((insertAfterNode.NodeType == NodeType.Paragraph) ||
    (insertAfterNode.NodeType == NodeType.Table)))
    {
        throw new ArgumentException("The destination node should be either paragraph or table.");
    }

    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;
    // This object will be translating styles and lists during the import.
    NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document,
    ImportFormatMode.KeepSourceFormatting);
    // Loop through all sections in the source document.
    foreach (Section srcSection in srcDoc.Sections)
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            // Do not insert node if it is a last empty paragarph in the section.
            Paragraph para = srcNode as Paragraph;
            if ((para != null) && para.IsEndOfSection && !para.HasChildNodes)
                break;
            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.ImportNode(srcNode, true);
            // Insert new node after the reference node.
            dstStory.InsertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;
        }
    }
}

Also note that you can’t use method overloads. So you should use the following script.

Dim comHelper
Set comHelper = CreateObject("Aspose.Words.ComHelper")
Dim dstDoc
Set dstDoc = comHelper.Open(Server.MapPath("dstDoc.doc"))
Dim srcDoc
Set srcDoc = comHelper.Open(Server.MapPath("srcDoc.doc"))
Dim methods
Set methods = CreateObject("AsposeComWrapper.Methods")
methods.InsertDocument dstDoc.Range.Bookmarks.Item\_2("myBookmark").BookmarkStart.ParentNode, srcDoc 'builder.CurrentParagraph, srcDoc
dstDoc.Save(Server.MapPath("out.doc"))

I hope this could help you.

Best regards.

I added the code above and when I get to this line in Excel:

methods.InsertDocument dstDoc.Range.Bookmarks.Item\_2("myBookmark").BookmarkStart.ParentNode, srcDoc 

I get this error:

Run-time error '-2147024894 (80070002)':

Could not load file or assembly 'Aspose.Words, Version=5.1.0.0,Culture=neutral,PublicKeyToken=716fcc553a201e56' or one of its dependencies. The system cannot find the file specified.

Any ideas?

Thanks!

Scott

Hi

Thanks for your request. Maybe you should register Aspose.Words assembly in the GAC. See the following comand.

gacutil /i C:\Program Files\Aspose\Aspose.Words\Bin\net2.0\Aspose.Words.dll

Best regards.

That worked!!!

Thank You very much for all your support!!!

Is there another way to do this? Or can I send something different than the node to InsertDocument?

Everything works great in Excel, and I figured that if working in Excel I could get it to work in the development tool I’m using, but I cannot get it to work.

I am using Cincom Socrates, which is very much like vb6 or vbscript in excel.

I’m thinking if I can try passing something different to the wrapper dll???

Thanks!

Hi

Thanks for your request. It is not quite clear for me why you need to pass something different than Node. Could you tell me what exactly does not work? Unfortunately I never used Cincom Socrates, so please clarify your request.

Best regards.

When I use InsertDocument, Aspose inserts a blank line at the bookmark and then the document. Is there any way to not insert the blank line?

Attached are my files used below:

afternode = one.doc

doc = two.doc

bmark = "ProductSOSInsert"

NewDoc = three.doc

Here is my InsertDocument function:

public void InsertDocument(String afterNode, String doc, String bmark, String NewDoc)
{
    Aspose.Words.License license = new Aspose.Words.License();
    license.SetLicense("c:\\users\\Aspose.Total.lic");
    Node insertAfterNode;
    Document dstDoc = new Document(afterNode);
    LoadFormat format = Document.DetectFileFormat(doc);
    Document srcDoc;
    if (format == LoadFormat.Unknown)
    {
        //If format is unknown, maybe this is HTML (issue #3955)
        try
        {
            srcDoc = new Document(doc, LoadFormat.Html, string.Empty);
        }
        catch
        {
            throw new ArgumentException("Input file format is unknown");
        }
    }
    else
    {
        srcDoc = new Document(doc);
    }
    try
    {
        insertAfterNode = dstDoc.Range.Bookmarks[bmark].BookmarkStart.ParentNode;
    }
    catch
    {
        throw new ArgumentException("Invalid arguments - AsposeComWrapper");
    }
    // We need to make sure that the specified node is either pargraph or table.
    if (!((insertAfterNode.NodeType == NodeType.Paragraph) ||
    (insertAfterNode.NodeType == NodeType.Table)))
        throw new ArgumentException("The destination node should be either paragraph or table.");
    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;
    // This object will be translating styles and lists during the import.
    NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document,
    ImportFormatMode.KeepSourceFormatting);
    // Loop through all sections in the source document.
    foreach (Aspose.Words.Section srcSection in srcDoc.Sections)
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            // Do not insert node if it is a last empty paragarph in the section.
            Aspose.Words.Paragraph para = srcNode as Aspose.Words.Paragraph;
            if ((para != null) && para.IsEndOfSection && !para.HasChildNodes)
                break;
            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.ImportNode(srcNode, true);
            // Insert new node after the reference node.
            dstStory.InsertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;
        }
    }
    dstDoc.Save(NewDoc);
}

Hi

Thanks for your inquiry. Please try using the following method for inserting document at bookmark.

public void InsertDocumentAtBookamrk(string bookmarkName, Document dstDoc, Document srcDoc)
{
    //Create DocumentBuilder
    DocumentBuilder builder = new DocumentBuilder(dstDoc);
    //Move cursor to bookmark and insert paragraph break
    builder.MoveToBookmark(bookmarkName);
    builder.Writeln();
    //Content of srcdoc will be inserted after this node
    Node insertAfterNode = builder.CurrentParagraph.PreviousSibling;
    //Content of first paragraph of srcDoc will be apended to this parafraph
    Paragraph insertAfterParagraph = insertAfterNode as Paragraph;
    //Content of last paragraph of srcDoc will be apended to this parafraph
    Paragraph insertBeforeParagraph = builder.CurrentParagraph;
    //We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;
    //Remove empty paragraphs from the end of document
    while (!srcDoc.LastSection.Body.LastParagraph.HasChildNodes)
    {
        srcDoc.LastSection.Body.LastParagraph.Remove();
    }
    //Loop through all sections in the source document.
    foreach (Section srcSection in srcDoc.Sections)
    {
        //Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            //Do not insert node if it is a last empty paragarph in the section.
            Paragraph para = srcNode as Paragraph;
            if ((para != null) && para.IsEndOfSection && (!para.HasChildNodes))
            {
                break;
            }
            //If current paragraph is first paragraph of srcDoc 
            //then appent its content to insertAfterParagraph
            if (para.Equals(srcDoc.FirstSection.Body.FirstParagraph))
            {
                foreach (Node node in para.ChildNodes)
                {
                    Node dstNode = dstDoc.ImportNode(node, true, ImportFormatMode.KeepSourceFormatting);
                    insertAfterParagraph.AppendChild(dstNode);
                }
                //If subdocument contains only one paragraph 
                //then copy content of insertBeforeParagraph to insertAfterParagraph
                //and remove insertBeforeParagraph
                if (srcDoc.FirstSection.Body.FirstParagraph.Equals(srcDoc.LastSection.Body.LastParagraph))
                {
                    while (insertBeforeParagraph.HasChildNodes)
                    {
                        insertAfterParagraph.AppendChild(insertBeforeParagraph.FirstChild);
                    }
                    insertBeforeParagraph.Remove();
                }
            }
            //If current paragraph is last paragraph of srcDoc 
            //then appent its content to insertBeforeParagraph
            if (para.Equals(srcDoc.LastSection.Body.LastParagraph))
            {
                Node previouseNode = null;
                foreach (Node node in para.ChildNodes)
                {
                    Node dstNode = dstDoc.ImportNode(node, true, ImportFormatMode.KeepSourceFormatting);
                    if (previouseNode == null)
                    {
                        insertBeforeParagraph.InsertBefore(dstNode, insertBeforeParagraph.FirstChild);
                    }
                    else
                    {
                        insertBeforeParagraph.InsertAfter(dstNode, previouseNode);
                    }
                    previouseNode = dstNode;
                }
            }
            else
            {
                //This creates a clone of the node, suitable for insertion into the destination document.
                Node newNode = dstDoc.ImportNode(srcNode, true, ImportFormatMode.KeepSourceFormatting);
                //Insert new node after the reference node.
                dstStory.InsertAfter(newNode, insertAfterNode);
                insertAfterNode = newNode;
            }
        }
    }
}

Hope this helps.

Best regards.

I was able to get this working but found another issue.

Part of the text that is inserted is not formatted correctly.

I attached three documents: one.doc, two.doc, completed.doc.

As you can see I inserted two.doc into one.doc and the text ‘Item Details’ is formatted in Times New Roman and the rest of the document is in Arial, which is correct.

Here is the code I used:

public void InsertDocumentAtBookmark(String afterNode, String doc, String bookmarkName, String NewDoc)
{
    // Create Document
    Document dstDoc = new Document(afterNode);
    Document srcDoc = new Document(doc);
    //Create DocumentBuilder
    DocumentBuilder builder = new DocumentBuilder(dstDoc);
    //Move cursor to bookmark and insert paragraph break
    builder.MoveToBookmark(bookmarkName);
    builder.Writeln();
    //Content of srcdoc will be inserted after this node
    Node insertAfterNode = builder.CurrentParagraph.PreviousSibling;
    //Content of first paragraph of srcDoc will be apended to this parafraph
    Aspose.Words.Paragraph insertAfterParagraph = insertAfterNode as Aspose.Words.Paragraph;
    //Content of last paragraph of srcDoc will be apended to this parafraph
    Aspose.Words.Paragraph insertBeforeParagraph = builder.CurrentParagraph;
    //We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;
    //Remove empty paragraphs from the end of document
    //while (!srcDoc.LastSection.Body.LastParagraph.HasChildNodes)
    //{
    // srcDoc.LastSection.Body.LastParagraph.Remove();
    //}
    //Loop through all sections in the source document.
    foreach (Aspose.Words.Section srcSection in srcDoc.Sections)
    {
        //Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            //Do not insert node if it is a last empty paragarph in the section.
            Aspose.Words.Paragraph para = srcNode as Aspose.Words.Paragraph;
            if ((para != null) && para.IsEndOfSection && (!para.HasChildNodes))
            {
                break;
            }
            //If current paragraph is first paragraph of srcDoc 
            //then appent its content to insertAfterParagraph
            if (para != null)
            {
                if (para.Equals(srcDoc.FirstSection.Body.FirstParagraph))
                {
                    foreach (Node node in para.ChildNodes)
                    {
                        Node dstNode = dstDoc.ImportNode(node, true, ImportFormatMode.KeepSourceFormatting);
                        insertAfterParagraph.AppendChild(dstNode);
                    }
                }
                //If current paragraph is last paragraph of srcDoc 
                //then appent its content to insertBeforeParagraph
                else if (para.Equals(srcDoc.LastSection.Body.LastParagraph))
                {
                    Node previouseNode = null;
                    foreach (Node node in para.ChildNodes)
                    {
                        Node dstNode = dstDoc.ImportNode(node, true, ImportFormatMode.KeepSourceFormatting);
                        if (previouseNode == null)
                        {
                            insertBeforeParagraph.InsertBefore(dstNode, insertBeforeParagraph.FirstChild);
                        }
                        else
                        {
                            insertBeforeParagraph.InsertAfter(dstNode, previouseNode);
                        }
                        previouseNode = dstNode;
                    }
                }
                else
                {
                    //This creates a clone of the node, suitable for insertion into the destination document.
                    Node newNode = dstDoc.ImportNode(srcNode, true, ImportFormatMode.KeepSourceFormatting);
                    //Insert new node after the reference node.
                    dstStory.InsertAfter(newNode, insertAfterNode);
                    insertAfterNode = newNode;
                }
            }
            else
            {
                //This creates a clone of the node, suitable for insertion into the destination document.
                Node newNode = dstDoc.ImportNode(srcNode, true, ImportFormatMode.KeepSourceFormatting);
                //Insert new node after the reference node.
                dstStory.InsertAfter(newNode, insertAfterNode);
                insertAfterNode = newNode;
            }
        }
    }
    dstDoc.Save(NewDoc);
}

Hi

Thanks for your inquiry. This occurs because formatting is applied to whole paragraph and when you insert document at bookmark only child nodes of first paragraph are imported. That’s why formatting is lost. I modified the method (see the attached code).

Best regards,

Now I am insterting a landscape document into a portrait and the landscape document is getting cut off.

Sample1.doc Page 4 is what I need.

Sample2.doc, which was created using Aspose.Words, is incorrect.

What do I need to change in the insertdocument code to correct this?

Thank You!

Hi

Thanks for your inquiry. I think in this case you should use AppendDocument method. Plese see the following link to learn how to combine documents.

https://reference.aspose.com/words/net/aspose.words/document/methods/appenddocument

Hope this helps.

Best regards.

Can you give me sample code using the Document.AppendDocument method for C#?

Hi

Thanks for your inquiry. Here is code example:

// Open documents
Document dstDoc = new Document("dst.doc");
Document srcDoc = new Document("src.doc");
// Append src document to dst document
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
// save dst document
dstDoc.Save("out.doc");

Best regards.

The issues you have found earlier (filed as WORDSNET-5251) have been fixed in this .NET update and this Java update.