Preserving format when inserting paragraph

Dear Aspose team!
Currently, I have a problem with inserting a Paragraph instance into a Bookmark.
Example 1:
I got a document which contains the following text, including a bookmark in the first bullet:
My hobbies are
- cooking [paragraph insertion bookmark]
- running
- reading
When I just insert text into the bookmark, everything works fine and the bullet format is preserved.
If I insert a paragraph which contains the text run "and certainly eating " into the bookmark, the result looks as follows:
My hobbies are
cooking
and certainly eating
running
- reading

Is there a way of preserving all the bullets (and other formatting like numbering etc.) as it works with “- reading”?
Example 2:
I got a similar document with the bookmark in an own bullet:
My hobbies are
- cooking
- [paragraph insertion bookmark]
- running
- reading
When inserting a paragraph containing
eating
walking
surfing
into the bookmark, I is formatted as follows:
My hobbies are
- cooking
eating
walking

surfing
running
- reading
Only the first and the last bullet is preserved; the other inserted texts are not formatted when inserting.
The result I would expect is:
My hobbies are
- cooking
- eating
- walking
- surfing
- running
- reading
Could you please tell me how I can achive my expected paragraph formattings?
Thanks in advance for your help,
cheers,
Stephan

Hi

Thanks for your inquiry. Maybe you should use DocumentBuilder in this case. Please see the following code and attached documents.

// Open document and create DocumentBuilder
Document doc = new Document(@"Test184\in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// move DocumentBuider cursor to bookmark
builder.MoveToBookmark("mybk");
// Insert few more paragraphs
builder.Write("eating\nwalking\nsurfing");
// Save output document
doc.Save(@"Test184\out.doc");

Or the following code:

// Open document and create DocumentBuilder
Document doc = new Document(@"Test184\in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// move DocumentBuider cursor to bookmark
builder.MoveToBookmark("mybk");
// Insert few more paragraphs
builder.Writeln("eating");
builder.Writeln("walking");
builder.Write("surfing");
// Save output document
doc.Save(@"Test184\out.doc");

Hope this helps.
Best regards,

Hi Alexey!
Thank you for your help!
In my case, adding strings by the DocumentBuilder will probably not help because the text is contained in an instance of class Paragraph (which is not known before the insertion and which potentially could contain more items than just a few text bullets).
I expected that each CompositeNode “knows” how it is formatted and just performs its formatting rules if sub nodes are added (as Word itself automatically does).
Is there a workaround like:
- using the DocumentBuilder by selecting a CompositeNode and then performing a formatting action on the node and its subnodes (as you can manually do in your Word application by selecting, using right-mouse and then bullet)?
Thanks a lot for your efforts,
cheers,
Stephan

Hi

Thank you for additional information. Please attach your document here and provide me sample code that demonstrates the issue.
Maybe you should just change formatting of the paragraph that you inserted at the bookmark.
Best regards.

Hi Alexey!
This is some sample code:

foreach(Section txmSection in txmDoc.Sections)
    {
        foreach(Node txmNode in txmSection.Body.ChildNodes)
        {
            // Only Paragraph or Table nodes can be inserted into Cell or Shape
            if (txmNode is Paragraph || txmNode is Table)
            {
                insertedNode = wordDoc.ImportNode(txmNode, true, ImportFormatMode.KeepSourceFormatting);
                CompositeNode currPosition = (CompositeNode) bmStartParentNode.ParentNode.ChildNodes[index];
                if (currPosition == null)
                {
                    bmStartParentNode.ParentNode.ChildNodes.Insert(index, insertedNode);
                }
                else
                {
                    currPosition.ParentNode.InsertAfter(insertedNode, currPosition);
                }
            }
        }

Annotiations:
txmDoc:
a text module as Document instance;
this keeps the Paragraph(or Table) Nodes which shall be inserted into the bookmark
bmStartParentNode :
the parent CompositeNode of the BookmarkStart of the Bookmark, in which the Paragraph (or Table) shall be inserted
What I haven’t tried yet:
change ImportFormatMode.KeepSourceFormatting to ImportFormatMode.UseDestinationStyles
I’ll try this now and then post my results.
Comming soon if the afore mentioned action won’t help:
some sample Word documents
Thank you for your efforts,
cheers,
Stephan

Hi Alexey!
Please find attached the sample files (I hope their names are self-describing enough).
I hope this will help - if there are still any questions, please feel free to ask.
Thank you very much,
cheers,
Stephan
p.s.:
importing the Node to be inserted by
ImportFormatMode.UseDestinationStyles
instead of
ImportFormatMode.KeepSourceFormatting
did not help.

Hi

Thank you for additional information. This is correct behavior, when you copy paragraph from another document and insert it into your document, the inserted paragraph should preserve its original formatting. (The same behavior you can see in MS Word, when you copy/paste entire paragraph)
If you need to create list item for each paragraph, you should create empty list item in your destination document and copy all child nodes of source paragraph. Please see the following code, for instance:

// Open template document
Document dstDoc = new Document(@"Test187\template_with_bookmark.docx");
// Create Document builder. it will help us to work with list items
DocumentBuilder builder = new DocumentBuilder(dstDoc);
// Open source document
Document srcDoc = new Document(@"Test187\text_module_to_be_inserted_into_bookmark.docx");
// Remove ald value from bookmark and move DocumentBuilder cursor to this bookmark
dstDoc.Range.Bookmarks["C8397Mod000000010001097R0000000025"].Text = string.Empty;
builder.MoveToBookmark("C8397Mod000000010001097R0000000025");
// Loop through paragraphs in the source document
foreach(Paragraph srcPar in srcDoc.FirstSection.Body.Paragraphs)
{
    // Import paragraph to the destination document
    Paragraph dstPar = (Paragraph) dstDoc.ImportNode(srcPar, true, ImportFormatMode.KeepSourceFormatting);
    // Copy all child nodes to the current paragraph of DocumentBuilder
    while (dstPar.HasChildNodes)
        builder.InsertNode(dstPar.FirstChild);
    // Insert paragraph break
    builder.Writeln();
}
// Remove empty paragraph
builder.CurrentParagraph.Remove();
// Save output document
dstDoc.Save(@"Test187\out.doc");

Hope this helps.
Best regards.

I forgot to post the index increment (exists in our code):

if (currPosition == null)
{
    bmStartParentNode.ParentNode.ChildNodes.Insert(index, insertedNode);
}
else
{
    currPosition.ParentNode.InsertAfter(insertedNode, currPosition);
}
index++;

Hi Alexey!
Thanks a lot for your reply and your sample code.
Did I get you right:
-our problem is that we insert whole Paragraph instances and not the paragraph 's child nodes (e.g. simple text runs)?
If so, then we should traverse each child node’s sub-node-tree, because each child node could be a CompositeNode again, right?
- we also could insert the child nodes directly (without using DocumentBuilder)?
Basically, we intent to keep the source Paragraph’s formatting. If we insert it into special pre-formatted ‘areas’ (like bullets), we would like the paragraph to adopt the area’s formatting.
I’m sorry, but I don’t understand the meaning of the
ImportFormatMode

argument at ImportNode()

Setting UseDestinationStyles should perform the styles of the destination document’s insertion point, shouldn’t it?
(e.g. ParagraphFormat)
The source docs of ImportFormatMode says

// When you copy nodes from one document to another, this option specifies how
// formatting is resolved when both documents have a style with the same name,
// but different formatting.


I think in my case, both documents have the “Normal” style but diffent formattings (e.g. bullets).
So the style names are matching…

I found the following issue:
<A href="https://forum.aspose.com/t/104024
Could this be related in some way?

Thank you again for your help,

cheers,

Stephan

Hi Stephan,

Thank you for additional information.

  1. Yes, the problem occurs because you insert whole paragraph. But in your case you need that paragraph becomes an item of the list in the destination document. That is why I advice to copy only child nodes from source paragraph. In this case, text formation will be fully preserved. Only paragraph formatting can be lost (e.g line spacing, right and left indents etc.). However, in your case paragraphs in source and in destination document has Normal style, so no formatting will be lost.
  2. No, you do not need to traverse tree of child nodes. You should just copy child nodes of source paragraph to the destination paragraph. As I showed in the code.
  3. Yes, you can insert child nodes directly without using DocumentBuilder. You can use AppendChild method. However, I think, DocumentBuilder makes it easier to create new paragraphs.
  4. Here you can learn more about ImportFormatMode:
    https://reference.aspose.com/words/net/aspose.words/importformatmode/
    The main difference between UseDestinationStyles and KeepSourceFormatting is that when you use UseDestinationStyles mode and if the destination document already contains style with the same name as in source document, this style will not be copied into the destination document. When you use KeepSourceFormatting mode, all styles will be copied into the destination document, if the destination document already contain style with the same name, style will be renamed and copied into the document.
  5. No, the issue mentioned in this thread is not related to your case.

Best regards.

Hi Alexey!
Thank you so much for your detailed help.
I think this issue is clear now for me!
Cheers,
Stephan

Hi Alexey!
It’s me again… :slight_smile:
I tried your sample code in a similar way and it works fine with preserving the original paragraph format (e.g. bullets).
But…
My first problem is:

  • Texts directly following the insertion bookmark are also formatted(e.g.with bullets) although they shouldn 't be formatted.*
    Example:
    If I insert…
    running
    walking
    reading
    …into the template…
    My hobbies are
  1. [insertion_bookmark]

And what are Your hobbies?
Please let me know.
…I get the following result:
My hobbies are

  1. running
  2. walking
  3. reading
  4. And what are Your hobbies?

Please let me know.
What I would expect is:
My hobbies are

  1. running
  2. walking
  3. reading

And what are Your hobbies?
Please let me know.
So text that is directly following the numbering part also gets a number. The text after the following one doesn’t (which is correct).
My second problem is:
DocumentBuilder#Writeln()
seems to trigger the bullet formatting of inserted text as the enter key in the Word application does, doesn’t it?
This works fine and is desired, but how can I perform a paragraph break without creating a new bullet?
This is required to avoid something like

  • running
  • walking
  • reading

And what are Your hobbies?
Please let me know.
To insert text module Documents, I tried things like

bool isLastNodeInModule = txmSection.Body.ChildNodes.IndexOf(txmNode) == txmSection.Body.ChildNodes.Count - 1;
bool isLastModule = txmDocs.IndexOf(txmDoc) == txmDocs.Count - 1;
if (isLastModule && isLastNodeInModule)
{
    documentBuilder.ListFormat.RemoveNumbers();
}
to avoid the last bullet

but this caused undesired effects like removing bullets at the wrong place.
Do you have any ideas what my problems could be?
If you wish some further sample code, please let me know.
Thank you very much for your help,
cheers,
Stephan

Hi Stephan,

Thanks for your request. Please try using DocumentBuilder.Write method when you insert the last item instead of using DocumentBuilder.Writeln. I think this should help.
Best regards.