How to navigate to every paragraph and insert a field at end of paragraph?

How to navigate to every paragraph and insert a field at end of paragraph?

@hrnallap

To navigate through every paragraph in a document and insert a field at the end of each paragraph using Aspose.Words, you can utilize the DocumentBuilder class. Below is a sample code snippet demonstrating how to achieve this in C#:

using Aspose.Words;
using Aspose.Words.Fields;

class Program
{
    static void Main()
    {
        // Load the document
        Document doc = new Document("YourDocument.docx");
        DocumentBuilder builder = new DocumentBuilder(doc);

        // Iterate through all paragraphs in the document
        foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true))
        {
            // Move the builder to the end of the current paragraph
            builder.MoveTo(paragraph);
            // Insert a field at the end of the paragraph
            builder.InsertField("MERGEFIELD YourFieldName");
        }

        // Save the modified document
        doc.Save("ModifiedDocument.docx");
    }
}

Explanation:

  1. Load the Document: The document is loaded using the Document class.
  2. Create a DocumentBuilder: An instance of DocumentBuilder is created to facilitate the insertion of content.
  3. Iterate Through Paragraphs: The code loops through each paragraph in the document using GetChildNodes.
  4. Move to Paragraph: The MoveTo method of DocumentBuilder is used to position the cursor at the end of the current paragraph.
  5. Insert Field: The InsertField method is called to insert a field at the end of the paragraph.
  6. Save the Document: Finally, the modified document is saved.

This approach allows you to dynamically insert fields at the end of each paragraph in your document. Adjust the field type and name as necessary for your specific use case.

Above reply is not inserting field at section end or paragraph end which is what we want.

@hrnallap Could you please attach your input and expected output documents here for our reference? We will check your documents and provide you more information.

Attaching our input document. We want to insert hyper link after every section as highlighted below.
1200-02-5908-006.docx (99.1 KB)

@hrnallap You can use the following simple code to insert hyperlink at the end of each paragraph in the document:

Document doc = new Document(@"C:\Temp\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true))
{
    builder.MoveTo(paragraph);
    builder.Font.StyleIdentifier = StyleIdentifier.Hyperlink;
    builder.InsertHyperlink("link", "https://google.com", false);
}

doc.Save(@"C:\Temp\out.docx");