Free Support Forum - aspose.com

Insert document at bookmark issue

Hi,

I’m using aspose.word for .net. I’ve an issue using these source methods:

Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing

'This is a Run node that contains either the beginning or the complete match.
Dim currentNode As Node = e.MatchNode

'The first (and may be the only) run can contain text before the match,
'in this case it is necessary to split the run.
If (e.MatchOffset > 0) Then
currentNode = SplitRun(CType(currentNode, Run), e.MatchOffset)
End If

'This array is used to store all nodes of the match for further removing.
Dim runs As New ArrayList()

'Find all runs that contain parts of the match string.
Dim remainingLength As Integer = e.Match.Value.Length
While ((remainingLength > 0) AndAlso (currentNode IsNot Nothing) AndAlso (currentNode.GetText().Length <= remainingLength))
runs.Add(currentNode)
remainingLength = remainingLength - currentNode.GetText().Length

'Select the next Run node.
'Have to loop because there could be other nodes such as BookmarkStart etc.
Do While ((currentNode IsNot Nothing) AndAlso (currentNode.NodeType <> NodeType.Run))
currentNode = currentNode.NextSibling
Loop

End While
'Split the last run that contains the match if there is any text left.

If ((currentNode IsNot Nothing) AndAlso (remainingLength > 0)) Then
SplitRun(CType(currentNode, Run), remainingLength)
runs.Add(currentNode)
End If

'Create Document Buidler and insert the object
Dim builder As New DocumentBuilder(e.MatchNode.Document)
builder.MoveTo(CType(runs(runs.Count - 1), Run))
If Me.mChecked Then
Dim paragraphs As Node() = e.MatchNode.Document.GetChildNodes(NodeType.Paragraph, True).ToArray()
'Remove paragraph if it is list item.
For Each paragraph As Aspose.Words.Paragraph In paragraphs
If (paragraph.IsListItem) AndAlso (paragraph.GetText.Contains(mText)) Then
If mTextReplace = “” Then
paragraph.Remove()
Else
paragraph.ListFormat.RemoveNumbers()
builder.Write(Me.mTextReplace)
End If
Exit For
ElseIf (paragraph.IsListItem = False) AndAlso (paragraph.GetText.Contains(mText)) Then
If mTextReplace = “” Then
paragraph.Remove()
End If
Exit For
End If
Next
ElseIf mType = “multiplo” Then 'if the object is a multiple object
Dim paragraphs As Node() = e.MatchNode.Document.GetChildNodes(NodeType.Paragraph, True).ToArray()
'Remove paragraph if it is list item.
For Each paragraph As Aspose.Words.Paragraph In paragraphs
If (paragraph.GetText.Contains(mText)) Then
builder.Writeln(mUrl)
builder.Write("#" & mText & “#”)
Exit For
End If
Next
ElseIf mType = “link” Then 'if the object is an Hyperlink
'builder.MoveTo(CType(runs(runs.Count - 1), Run))
builder.Font.StyleIdentifier = StyleIdentifier.Hyperlink
If (mUrl.Substring(0, 4) <> “http”) Then
builder.InsertHyperlink(mText, “http://” & mUrl, False)
Else
builder.InsertHyperlink(mText, mUrl, False)
End If
ElseIf mType = “image” Then 'if the object is an image
Dim ImageStream As MemoryStream
Dim NewImage As System.Drawing.Image
ImageStream = New MemoryStream(mImage)
NewImage = System.Drawing.Image.FromStream(ImageStream)
builder.InsertImage(NewImage)
ElseIf mType = “document” Then 'if the object is a document to append
builder.StartBookmark(mBook)
builder.EndBookmark(mBook)
Utils_Aspose.InsertDocumentByBookMark(mBook, mDoc, mSrcDoc)
End If

'Now remove all runs in the sequence.
For Each run As Run In runs
run.Remove()
Next
'Signal to the replace engine to do nothing because we have already done all what we wanted.
Return ReplaceAction.Skip

End Function

Public Shared Sub InsertDocumentByBookMark(ByVal bookmarkName As String, ByVal dstDoc As Document, ByVal srcDoc As Document, Optional ByVal logger As log4net.ILog = Nothing)
logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
logger.Info("START: " + System.Reflection.MethodBase.GetCurrentMethod().ToString)
Try
Dim importer As New NodeImporter(srcDoc, dstDoc, ImportFormatMode.UseDestinationStyles)
’ Create DocumentBuilder
Dim builder As New DocumentBuilder(dstDoc)

’ Move cursor to bookmark and insert paragraph break
builder.MoveToBookmark(bookmarkName)
builder.Writeln()

’ If current paragraph is a list item, we should clear its formating.
If (builder.CurrentParagraph.IsListItem) Then
builder.ListFormat.RemoveNumbers()
End If

’ Content of srcdoc will be inserted after this node
Dim insertAfterNode As Node = builder.CurrentParagraph.PreviousSibling

'Content of first paragraph of srcDoc will be apended to this parafraph
Dim insertAfterParagraph As Aspose.Words.Paragraph = Nothing
If (insertAfterNode.NodeType = NodeType.Paragraph) Then
insertAfterParagraph = CType(insertAfterNode, Aspose.Words.Paragraph)
End If

’ Content of last paragraph of srcDoc will be apended to this parafraph
Dim insertBeforeParagraph As Aspose.Words.Paragraph = builder.CurrentParagraph
’ We will be inserting into the parent of the destination paragraph.
Dim dstStory As CompositeNode = insertAfterNode.ParentNode
’ Remove empty paragraphs from the end of document
While (Not DirectCast(srcDoc.LastSection.Body.LastChild, CompositeNode).HasChildNodes)
srcDoc.LastSection.Body.LastParagraph.Remove()
If (srcDoc.LastSection.Body.LastChild Is Nothing) Then
Exit While
End If
End While

’ Loop through all sections in the source document.
For Each srcSection As Aspose.Words.Section In srcDoc.Sections
'Loop through all block level nodes (paragraphs and tables) in the body of the section.
For nodeIdx As Integer = 0 To srcSection.Body.ChildNodes.Count - 1
Dim srcNode As Node = srcSection.Body.ChildNodes(nodeIdx)
’ Do not insert node if it is a last empty paragarph in the section.
Dim para As Aspose.Words.Paragraph = Nothing
If (srcNode.NodeType = NodeType.Paragraph) Then
para = CType(srcNode, Aspose.Words.Paragraph)
End If

If ((Not para Is Nothing) AndAlso para.IsEndOfSection AndAlso (Not para.HasChildNodes)) Then
Exit For
End If

’ If current paragraph is first paragraph of srcDoc
’ then appent its content to insertAfterParagraph
Dim nodeInserted As Boolean = False
If ((Not para Is Nothing) AndAlso para.Equals(srcDoc.FirstSection.Body.FirstChild)) Then
nodeInserted = True ’ set this flag to know that we already processed this node.
For i As Integer = 0 To para.ChildNodes.Count - 1
Dim node As Node = para.ChildNodes(i)
Dim dstNode As Node = importer.ImportNode(node, True)
insertAfterParagraph.AppendChild(dstNode)
Next

’ 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.LastChild)) Then
While (insertBeforeParagraph.HasChildNodes)
insertAfterParagraph.AppendChild(insertBeforeParagraph.FirstChild)
End While
insertBeforeParagraph.Remove()
End If
End If

’ If current paragraph is last paragraph of srcDoc
’ then appent its content to insertBeforeParagraph
If ((Not para Is Nothing) AndAlso para.Equals(srcDoc.LastSection.Body.LastChild)) Then
nodeInserted = True ’ set this flag to know that we already processed this node.
Dim previouseNode As Node = Nothing
For i As Integer = 0 To para.ChildNodes.Count - 1
Dim node As Node = para.ChildNodes(i)
Dim dstNode As Node = importer.ImportNode(node, True)
If (previouseNode Is Nothing) Then
insertBeforeParagraph.InsertBefore(dstNode, insertBeforeParagraph.FirstChild)
Else
insertBeforeParagraph.InsertAfter(dstNode, previouseNode)
End If
previouseNode = dstNode
Next
End If

If (Not nodeInserted) Then
’ This creates a clone of the node, suitable for insertion into the destination document.
Dim newNode As Node = importer.ImportNode(srcNode, True)
’ Insert new node after the reference node.
dstStory.InsertAfter(newNode, insertAfterNode)
insertAfterNode = newNode
End If
Next
Next
Catch ex As Exception
logger.Error("InsertDocumentByBookMark(): " + ex.Message)
End Try
logger.Info("END: " + System.Reflection.MethodBase.GetCurrentMethod().ToString)
End Sub

When I insert the other_word.doc document (in IReplacingCallback_Replacing type=“document”) the program will crash.
In any case, when the program don’t crash, the last line of the source document into the destination document lose his formatting (it takes the font of the destination document, if there is a bullet it will be lose etc etc., as you can see in the attached files).

Can you help me please??

Hi

Thanks for your inquiry. As I can see in your case, your source document should start form a new paragraph and the last paragraph of the source document should be also inserted as a separate paragraph. In this case, I suppose you do not need to use InsertDocumentAtBookmark method, it would be enough to use InsertDocument method. Here is a modified code:

ElseIf mType = "document" Then 'if the object is a document to append

Dim insertAfter As Paragraph = builder.CurrentParagraph;

builder.Writeln()

' Insert a document right after the current paragraph.

InsertDocument(insertAfter, mSrcDoc)

End If

You can find source code of InsertDocument method here:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/howto-insert-a-document-into-another-document.html

Hope this helps.

Best regards,

Thank you for the reply.

Ok in this case this is better, but I have more case, what must I do to in my code to recognize when I have to use the insertDocument and when I have to use the InsertDocumentAtBookmark?

Ivan

I try your solution but it doesn’t works for me. In the template I insert a document at the last tag (the red tag), and the document will be append after the bullet list (and aftter the document it will be inserted an extra bullet list, but I resolve it with a builder.write).


Ivan

Other Issue:


When I insert the OtherWord.doc document the program will crash when it has to remove all run in the sequence

Hello

Thank you for additional information. I cannot reproduce the problem with your documents on my side using the latest version of Aspose.Words. Could you create simple application which allows me to reproduce this problem on my side?

Best regards,

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


This message was posted using Notification2Forum from Downloads module by aspose.notifier.
(24)