How to Format Font Style and Paragraph Style for WordDocument In VB.Net

Hi To All,

I expect to use Aspose.Words.dll to Format Font Style and Paragraph Style in VB.net, how to write the codes?
My Codes in VBA are as following:
-----------VBA Code -------------
Dim SelSt as long ’ at what position the cursor will be moved
Dim AddText as string ’ the text that will be inserted into the document
SelSt =120
AddText=“D”
Set WordApp=CreateObject(“Word.Application”) 'Create Office Word Application Object
WordApp.Selection.start = SelSt 'Move the cursor to the position at SelSt
WordApp.Selection.End = SelSt
WordApp.Selection.TypeText Text:=AddText 'Insert the Addtext into Document at the SelSt Position
WordApp.Selection.MoveLeft unit:=1, Count:=1 'move the cursor to left
WordApp.Selection.MoveRight unit:=1, Count:=1, Extend:=1 'Select the added text
With WordApp.Selection.Font 'format the fontstyle of the selected added text
.Size = 1 'set the fontsize of the selected added text to 1
.Scaling = 1
.Position = 0
.Kerning = 1
.Spacing = -1 ’ squeeze the added selected text
.Animation = 0
.DisableCharacterSpaceGrid = False
.EmphasisMark = 0
.Color = Color 'Set the color of the selected added text
End With
WordApp.Selection.MoveLeft unit:=1, Count:=1, Extend:=1 'Select the added text
WordApp.Selection.Font.Color = Color 'Set the color of the selected added text
WordApp.Selection.Font.Size = 1 'set the fontsize of the selected added text to 1
WordApp.Selection.MoveLeft unit:=1, Count:=1 'Unselect the selected added text
--------End VBA Code -------------

my question is how to convert the VBA code into VB.Net code based on Aspose.Words.dll?

Thanks for your help and solution!

Chen

@jixuecheng

Thank you for your inquiry. Please have have a look at this Run Class with example sample codes and complete documentation for Aspose.Words for .NET API 17.12.

I expect to use Aspose.Words.dll to Format Font Style and Paragraph Style in VB.net, how to write the codes?
my question is how to convert the VBA code into VB.Net code based on Aspose.Words.dll?

Please have a look at this sample code to start.

    Dim doc As New Aspose.Words.Document("E:\Aspose\Test.docx")

    Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)
    For Each run As Run In runs
        If run.Font.Hidden Then
            run.Font.Hidden = False
        End If

        If run.Font.Italic = True Then
            run.Font.Italic = False
            run.Font.Size = 16
            run.Font.Underline = Underline.Single
        End If
    Next

    doc.Save("E:\Aspose\Test_out.docx")

Dear Rizwan,

Thanks for your answer.
The sample is only for formatting fontstyle.
And Could you help me how to move the cursor at a given position, and then select some text, and finally format the fontstyle of the selected text like what showed in VBA Codes?

@jixuecheng

Thank you for your feedback. You can move cursor as a DocumentBuilder to a specific paragraph and using Run you can format the paragraph contents. Please have a look at this sample code.

    Dim doc As New Aspose.Words.Document("E:\Aspose\Test.docx")
    ' Initiate builder
    Dim builder As New DocumentBuilder(doc)

    ' Move builder to specific paragraph.
    builder.MoveToParagraph(1, 1)

    ' Get current paragrapgh to format
    Dim currentPara As Paragraph = builder.CurrentParagraph

    Console.WriteLine(currentPara.GetText())
    ' Get Child of current paragrapgh for formating
    For Each run As Run In currentPara.GetChildNodes(NodeType.Run, True)
        Console.WriteLine("Run Text:  " + run.Text)

        ' Check if content is styled as Italic
        If run.Font.Italic Then
            run.Font.Italic = False
            run.Font.Size = 18
            run.Font.Bold = True
        End If

        ' Check if content text contains to e.g 'Aspose'
        If run.GetText().Contains("Aspose") Then
            run.Font.Italic = True
            run.Font.Size = 30
            run.Font.Bold = True
        End If
    Next

    doc.Save("E:\Aspose\Test_out.docx")

Dear Rizwan,

Thanks for your solution and demo. Unfortunately, it still cannot achieve my goal. The followings are some questions, would you please continue to help me with Vb.net codes?

Question 1: How to get the paragraph count of a documnet?
---------My Vb.Net Codes---------------
Dim doc As New Aspose.Words.Document(“H:\Test.docx”)
Dim builder As New DocumentBuilder(doc)
Dim ParagraphCount As Long = builder.Document.BuiltInDocumentProperties.Paragraphs
the problem is that the ParagraphCount always gets 1. In fact, the document maybe have more than 1 or 10 or 100 paragraphs. Why does the ParagraphCount always gets 1?
-------End Codes------------------

Question 2: How to move the cursor to a given position of a given paragraph?
---------My Vb.Net Codes---------------
Dim doc As New Aspose.Words.Document(“H:\Test.docx”)
Dim builder As New DocumentBuilder(doc)
Dim ParagraphCount As Long = builder.Document.BuiltInDocumentProperties.Paragraphs
for Pi as long=1 to ParagraphCount
builder.MoveToParagraph(Pi, 1) 'move the cursor to any paragraph, such as Pi=5
Console.WriteLine(“Demo”)
'Do something here
next
doc.Save(“H:\Test2.docx”)
the problem is that there is no “Demo” existing in Test2.docx at the fifth Paragraph, and the cursor always be moved to the head of the first paragraph.
-------End Codes------------------

Question 3: How to select any char or chars among a given paragraph for formatting its fontstyle?
---------My Vb.Net Codes---------------
Dim doc As New Aspose.Words.Document(“H:\Test.docx”)
Dim builder As New DocumentBuilder(doc)
Dim ParagraphCount As Long = builder.Document.BuiltInDocumentProperties.Paragraphs
Dim CharPosition as integer,CharsLen as long
for Pi as long=1 to ParagraphCount
builder.MoveToParagraph(Pi, CharPosition ) 'move the cursor to any paragraph, such as Pi=5, and set the cursor at any position of the specified paragraph, such as CharPosition =6
'if the text of the paragraph is “I’m a new user of Aspose.Words.dll.”, How to select the chars such as “user” and then format its fontstyle?
next
doc.Save(“H:\Test2.docx”)
-------End Codes------------------

@jixuecheng

Thank you for writing back.

Question 1: How to get the paragraph count of a documnet?

You can get the document paragraphs count as:

    ' Get all document Paragraphs
    Dim paragraphsCollection As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)

    ' Get count of paragraphs
    Dim paraCount As Integer = paragraphsCollection.Count

Question 2: How to move the cursor to a given position of a given paragraph?

    ' Initia builder
    Dim builder As New DocumentBuilder(doc)

    ' Move builder to specific paragraph e.g first pragraph.
    builder.MoveToParagraph(1, 1)

    ' Get current paragraph at builder cursor is currently moved to format
    Dim currentPara As Paragraph = builder.CurrentParagraph

Question 3: How to select any char or chars among a given paragraph for formatting its fontstyle?

You can traverse the paragraph text using Run and then can apply custom logic to to specific word/character. Please have a look at this sample code that is applying Font.Size as 60 for word “user” in first paragraph.

    ' Get Child of current paragraph for formatting
    For Each run As Run In currentPara.GetChildNodes(NodeType.Run, True)
        If run.Text.Contains("user") Then
            Dim runsplits As Array = run.Text.Split(" ")
            For Each Str As String In runsplits
                Dim runAfter As Run = run.Clone(True)
                If Str.Equals("user") Then
                    runAfter.Text = "user"
                    runAfter.Font.Size = 60
                    run.ParentNode.InsertAfter(runAfter, run)
                Else
                    runAfter.Text = Str
                    run.ParentNode.InsertAfter(runAfter, run)
                End If
            Next
            Exit For
        End If
    Next

Dear Rizwan,

Thanks for your samples. Unfortunately ,there are still a lot of problems,would you be glad to continue to help me? Please refer to the following Image for a demo docx.
Test.jpg (19.8 KB)

Question 1: the cursor cannot be located at any position of a document.

Dim doc As New Aspose.Words.Document(“H:\Test\Test.docx”)
Dim builder As New DocumentBuilder(doc)
Dim paragraphsCollection As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
Dim paraCount As Long = paragraphsCollection.Count ’ paraCount gets 8
For pi As Long = 1 To paraCount
builder.MoveToParagraph(pi, 1) 'When Pi>1, it throws an exception. Why?
Dim currentPara As Paragraph = builder.CurrentParagraph
Dim MyTxt As String = currentPara.Range.Text
’ When Pi=1, the MyTxt =“0ParagraphoneNoSpacebetweenWord”, however,when Pi=2, the MyTxt is still equal to “0ParagraphoneNoSpacebetweenWord”, whereas the value of MyTxt should be “11ParagraphoneNoSpacebetweenWord1”. What’s wrong? How to move the cursor to a given paragraph?
next

Question 2: How to set the FirstLineIndent with 2 chars’ width for a document in batch

    Dim doc As New Aspose.Words.Document("H:\Test\Test.docx")
    Dim builder As New DocumentBuilder(doc)
    Dim paragraphsCollection As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
    For Each PC As Paragraph In paragraphsCollection
        PC.ParagraphFormat.FirstLineIndent = 24  'this method can set FirstLineIndent  for each paragraph, but its efficiency is too slow! Is there any high efficient method to perform this function?
    Next

Question 3: How to add text into a given position of any given paragraph, and then format the fontstyle of added text?

    Dim doc As New Aspose.Words.Document("H:\Test\Test.docx")
    Dim builder As New DocumentBuilder(doc)
    Dim paragraphsCollection As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
  Dim paraCount As Long = paragraphsCollection.Count   '  paraCount  gets 8
         Dim CurPos as long

    For pi As Long = 1 To paraCount
       builder.MoveToParagraph(pi, 1)  'When Pi>1, why it throws an exception?
        Dim currentPara As Paragraph = builder.CurrentParagraph
          CurPos =0
      For Each run As Run In currentPara.GetChildNodes(NodeType.Run, True)
         Dim runsplits As Array = run.Text.Split("")  ' there is no space between the chars, how to split them?
         For Each Str As String In runsplits
             Dim runAfter As Run = run.Clone(True)
             CurPos =CurPos +1
             if CurPos=3 then
               'the added text "Demo" is expected to be inserted into each paragraph at char index=3, therefore, the correct result is "0PaDemoragraphoneNoSpacebetweenWord", why its output is "0ParagraphDemooneNoSpacebetweenWord"? the output is out of expectation!
               runAfter.Text = "Demo"
               Run.Font.Italic = False
               Run.Font.Bold = False
              Run.Font.Size = 5
              Run.Font.Underline = Underline.None
              Run.Font.Scaling = 1
              Run.Font.Position = 0
             Run.Font.Kerning = 1
               Run.Font.Spacing = 10
              Run.Font.Color = Color.Red
             Run.ParentNode.InsertAfter(runAfter, Run)
        '   the added text "Demo" is expected to be font-formatted, but the output is out of expectation, it is "h" not "Demo" that has been font-formatted! why? how to achieve this goal?
            next
        next
    next
    Next

@jixuecheng

Thank you for writing back.

Paragraph Index starts from 0 and loop will be

For pi As Long = 0 To paraCount - 1

Please use MoveToParagraph(pi, 0) 0 as character index to move cursor to start of the paragraph and -1 for end of the paragraph and to get the paragraph text you can also use use currentPara .GetText(). Please have a look at this sample code.

    For pi As Long = 0 To paraCount - 1
        builder.MoveToParagraph(pi, 0)
        Dim currentPara As Paragraph = builder.CurrentParagraph
        Dim MyTxt As String = currentPara.GetText()
        Console.WriteLine("MyTxt: " + MyTxt)
    Next

FirstLineIndent property can be set for Paragraph or Lists objects same as you have shared.

Instead of splitting the string you can also get the Substring.

Please note these (Split & Substring) are not the Aspose.Words functions and we have shared the logic Split as an example of manipulating the Runs strings. You can write your own logic to concatenate the string as per your requirement. Please have a look at this sample code to achieve this result 0PaDemoagraphoneNospacebetweenWord.

    For pi As Long = 0 To paraCount - 1
        builder.MoveToParagraph(pi, 0)
        Dim currentPara As Paragraph = builder.CurrentParagraph
        Dim MyTxt As String = currentPara.Range.Text
        Console.WriteLine("MyTxt: " + MyTxt)
        For Each run As Run In currentPara.GetChildNodes(NodeType.Run, True)
            If pi = 0 Then ' Inserting word "Demo" for Font Styling for 1st paragraph after 3 characters. 
                If run.Text.Length > 2 Then
                    Console.WriteLine("Run Text: " + run.Text)
                    Dim strPostFix = run.Text.Substring(4, run.Text.Length - 4)
                    Dim runAfter As Run = run.Clone(True)
                    runAfter.Text = run.Text.Substring(0, 3)
                    run.Text = ""

                    run.ParentNode.InsertBefore(runAfter, run)
                    runAfter = run.Clone(True)

                    runAfter.Text = "Demo"
                    runAfter.Font.Italic = True
                    runAfter.Font.Bold = True
                    runAfter.Font.Size = 14
                    runAfter.Font.Underline = Underline.Single
                    'runAfter.Font.Color = Color.Red

                    run.ParentNode.InsertAfter(runAfter, run)

                    Dim runPostFix As Run = run.Clone(True)
                    runPostFix.Text = strPostFix

                    run.ParentNode.InsertAfter(runPostFix, runAfter)

                    Exit For
                End If
            End If
        Next
    Next