We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Change Font Style to Italic in Word Document | C# .NET

Hi,

I have similar issue where I need to change font style o italic for word “in vivo” when I have used above code it throwing me this error
"Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name ‘ReplaceEvaluatorArgs’ could not be found (are you missing a using directive or an assembly reference?) AsposeLibraryWord C:\Users\User\Desktop\BugFixes-Automatiq\DocsToSend\AsposeLibraryWord-Bugs\AsposeLibraryWord\Program.cs 34 Active
"
Can I know how to resolve this.

Hi,

PFA the code I tried.

using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Fields;
using Aspose.Words.Lists;
using Aspose.Words.Replacing;
using Aspose.Words.Tables;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
using Paragraph = Aspose.Words.Paragraph;
using Table = Aspose.Words.Tables.Table;

namespace AsposeLibraryWord
{
    class Program
    {
        private ReplaceAction ReplaceInsertMergeField(object sender, ReplaceEvaluatorArgs e)

        {//Get MatchNode

            Aspose.Words.Run run1 = (Aspose.Words.Run)e.MatchNode;

            //Create Run

            Aspose.Words.Run run2 = (Aspose.Words.Run)run1.Clone(true);

            //Get index of match value

            int index = run1.Text.IndexOf(e.Match.Value);

            //split run that contains matched text

            run2.Text = run1.Text.Substring(index + e.Match.Value.Length);

            run1.Text = run1.Text.Substring(0, index);

            run1.ParentParagraph.InsertAfter(run2, run1);

            //Create document builder

            DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document);

            //Move to run2

            builder.MoveTo(run2);

            //Change font

            builder.Font.Bold = true;

            builder.Font.Italic = true;

            //Insert value

            builder.Write(e.Match.Value);

            return ReplaceAction.Skip;

        }

        static void Main(string[] args)
        {
            string fileName = @"D:/PWS/Automation/inputdoc.docx";
            Aspose.Words.Document doc = new Aspose.Words.Document(fileName);

            doc.StartTrackRevisions("Test");
            DocumentBuilder builder = new DocumentBuilder(doc);


            foreach (Aspose.Words.Run run in doc.GetChildNodes(NodeType.Run, true))
            {
                string text = run.GetText();
               
            }
            Regex regex = new Regex("word");
            doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceInsertMergeField), false);

            doc.StopTrackRevisions();
            string dataDir = @"D:/PWS/Automation/ConvertedDOC.docx";
            doc.Save(dataDir);

        }
    }
}

@kkumaranil485,

Please compress the following resources into ZIP format and attach the .zip file here for testing:

  • A simplified source Word DOCX document
  • Aspose.Words generated DOCX file showing the undesired output (if any)
  • Your expected DOCX file showing the desired output. You can create this file manually by using MS Word.
  • Please also create a standalone simplified Console Application (source code without compilation errors) that helps us to reproduce this problem on our end and attach it here for testing. Please do not include Aspose.Words DLL files in it to reduce the file size.

As soon as you get these pieces of information ready, we will then start further investigation into your particular scenario and provide you more information.

Hi @awais.hafeez

Above the code which is throwing error that I have shared. I have tried with the above code which has same scenario where I need yo change “in vivo” from italics to normal text.

Hi,

PFA of documents for the same.
ItalicsFontToNormal.zip (27.6 KB)

@kkumaranil485,

You can meet this requirement by using following c# code of Aspose.Words for .NET API:

Document doc = new Document("C:\\Temp\\ItalicsFontToNormal\\inputdoc.docx");

FindReplaceOptions opts = new FindReplaceOptions();
opts.ReplacingCallback = new FindReplaceHandler();

doc.Range.Replace("In vivo", "", opts);
doc.Range.Replace("In vitro", "", opts);
doc.Range.Replace("sithu adljc eg ajcnlka", "", opts);

doc.Save("C:\\Temp\\ItalicsFontToNormal\\21.9.docx");

private class FindReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = 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)
            currentNode = SplitRun((Run)currentNode, e.MatchOffset);

        // This array is used to store all nodes of the match for further removing.
        ArrayList runs = new ArrayList();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.Match.Value.Length;
        while (
            (remainingLength > 0) &&
            (currentNode != null) &&
            (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
            {
                currentNode = currentNode.NextSibling;
            }
            while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
        }

        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0))
        {
            SplitRun((Run)currentNode, remainingLength);
            runs.Add(currentNode);
        }

        //Now Clear Formatting of all runs in the sequence.
        foreach (Run run in runs)
            run.Font.ClearFormatting();

        return ReplaceAction.Skip;

    }

    private static Run SplitRun(Run run, int position)
    {
        Run afterRun = (Run)run.Clone(true);
        afterRun.Text = run.Text.Substring(position);
        run.Text = run.Text.Substring((0), (0) + (position));
        run.ParentNode.InsertAfter(afterRun, run);
        return afterRun;
    }
}