Find Identical Bookmarks & Extract or Copy Bookmark's Content into another Word Document using C# .NET

I have two documents with same bookmark name and wanted to copy bookmark content from one document to another document.But Bookmark end throwing exception.

public void CopyBookmarkContentBetweenDocuments(List<string> bookmarkNames, string sourceFileName, string destinationFileName)
{
	var sourceDocument = new Document(sourceFileName);
	var destinationDocument = new Document(destinationFileName);

	foreach (var bookmarkName in bookmarkNames)
	{

		Bookmark bookmarkSourceDocument = CommonFunction.FindBookmark(sourceDocument, bookmarkName);
		if (bookmarkSourceDocument == null)
			continue;

		Bookmark bookmarkDestinationDocument = CommonFunction.FindBookmark(destinationDocument, bookmarkName);
		if (bookmarkDestinationDocument == null)
			continue;
		bookmarkDestinationDocument.Text = "";  // Remove possibly nodes enclosed by bookmark in destination document
		bookmarkDestinationDocument = CommonFunction.FindBookmark(destinationDocument, bookmarkName); // Get bookmark again. Necessary?

		NodeImporter imp = new NodeImporter(sourceDocument, destinationDocument, ImportFormatMode.KeepSourceFormatting);


		foreach (Node node in bookmarkSourceDocument.BookmarkStart.ParentNode)
		{
			Node impNode = imp.ImportNode(node, true);
			bookmarkDestinationDocument.BookmarkStart.ParentNode.AppendChild(impNode);
		}

	}
	destinationDocument.Save(destinationFileName);
}

26dbb9c8-59fc-4862-8630-6fd08d3a3669.zip (40.1 KB)
Saksfremlegg.Docx Source document and SaksprotokollElements.Docx destination document

26dbb9c8-59fc-4862-8630-6fd08d3a3669.zip (40.1 KB)

@SangeeN,

After an initial test with the licensed latest (20.6) version of Aspose.Words for .NET , we were unable to reproduce any exception on our end. Please see this output DOCX document and try running the following code:

C# Code:

var sourceDocument = new Document("E:\\Temp\\26dbb9c8-59fc-4862-8630-6fd08d3a3669\\Saksfremlegg.docx");
var destinationDocument = new Document("E:\\Temp\\26dbb9c8-59fc-4862-8630-6fd08d3a3669\\SaksprotokollElements.docx");

StringBuilder sb = new StringBuilder();
foreach (Bookmark bm in sourceDocument.Range.Bookmarks)
    sb.Append(bm.Name + ",");

string[] bookmarkNames = sb.ToString().Split(new char[] { ',' });

foreach (string bookmarkName in bookmarkNames)
{
    if (bookmarkName == "")
        continue;

    Bookmark bookmarkSourceDocument = sourceDocument.Range.Bookmarks[bookmarkName];
    if (bookmarkSourceDocument == null)
        continue;

    Bookmark bookmarkDestinationDocument = destinationDocument.Range.Bookmarks[bookmarkName];
    if (bookmarkDestinationDocument == null)
        continue;
    bookmarkDestinationDocument.Text = "";  // Remove possibly nodes enclosed by bookmark in destination document
    bookmarkDestinationDocument = destinationDocument.Range.Bookmarks[bookmarkName]; // Get bookmark again. Necessary?

    NodeImporter imp = new NodeImporter(sourceDocument, destinationDocument, ImportFormatMode.KeepSourceFormatting);

    foreach (Node node in bookmarkSourceDocument.BookmarkStart.ParentNode)
    {
        Node impNode = imp.ImportNode(node, true);
        bookmarkDestinationDocument.BookmarkStart.ParentNode.AppendChild(impNode);
    }

}
destinationDocument.Save("E:\\Temp\\26dbb9c8-59fc-4862-8630-6fd08d3a3669\\20.6.docx");

So, we suggest you please upgrade to the latest version.

Hi @awais.hafeez In Oppsummering part the whole content should be copied but only one line is copied to the destination document.

Oppsummering

Dette saksfremlegget kan oppsummeres med flg:

Should be like this,

Oppsummering

Dette saksfremlegget kan oppsummeres med flg:

  • Dette er en tekst med fet skrift

  • Dette er en tekst i kursiv

  • Dette tekst med undeline

  • Dette er alt

  • Første punkt i en bullet liste

  • Andre punkt

image.png (3.5 KB)

Output document should be like attachedSaksprotokollElements_after.zip (12.6 KB)

@SangeeN,

I think, you can implement the following workflow to meet this requirement:

  1. Extract complete content from a Bookmark in source document
  2. Move cursor to matching Bookmark’s location in destination document
  3. Insert extracted Document at destination bookmark’s place

@awais.hafeez I have already tried this approach and I am getting exception in Extract when there is no nextSection. image.png (35.0 KB)

public void CopyBookmarkContentBetweenDocuments(List<string> bookmarkNames, string sourceFileName, string destinationFileName)
{
	var sourceDocument = new Document(sourceFileName);
	var destinationDocument = new Document(destinationFileName);
	var builder = new DocumentBuilder(destinationDocument);
	string fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Data\\ExtractFile.doc");
	Document extractDoc = new Document(fileName);
	foreach (var bookmarkName in bookmarkNames)
	{
		try
		{
			Bookmark bookmarkSourceDocument = CommonFunction.FindBookmark(sourceDocument, bookmarkName);
			if (bookmarkSourceDocument == null)
				continue;

			Bookmark bookmarkDestinationDocument = CommonFunction.FindBookmark(destinationDocument, bookmarkName);
			if (bookmarkDestinationDocument == null)
				continue;
			bookmarkDestinationDocument.Text = "";  // Remove possibly nodes enclosed by bookmark in destination document
			bookmarkDestinationDocument = CommonFunction.FindBookmark(destinationDocument, bookmarkName); // Get bookmark again. Necessary?

			ArrayList extractedNodesInclusive = CommonFunction.ExtractContent(bookmarkSourceDocument.BookmarkStart, bookmarkSourceDocument.BookmarkEnd, true);
			Document dstDoc = CommonFunction.GenerateDocument(extractDoc, extractedNodesInclusive);
			builder.MoveToBookmark(bookmarkName, false, true);
			builder.InsertDocument(extractDoc, ImportFormatMode.KeepSourceFormatting);



		}
		catch (Exception ex)
		{

		}
	}
	destinationDocument.Save(destinationFileName);
} 

@SangeeN,

You are right; we managed to reproduce this exception using the following Documents and Project:

The ID of this issue is WORDSNET-20709. We will further look into the details of this problem and will keep you updated on the status of the linked issue. We apologize for your inconvenience.

@awais.hafeez Is there any update on this issue?

@SangeeN,

I am afraid, your issue is currently pending for analysis and is in the queue. We will inform you via this forum thread as soon as this issue will get resolved in future. We apologize for any inconvenience.

@SangeeN,

Regarding WORDSNET-20709, it is to update you that the exception does no longer occur when using the code from Common.cs with latest 20.11 version of Aspose.Words for .NET on our end. We have now closed this issue; so, please upgrade to the latest version and use the new code from Common.cs class.

The issues you have found earlier have been fixed in this Aspose.Words for .NET 20.12 update and this Aspose.Words for Java 20.12 update.