世俱杯 2025

Aspose.Words如何实现高亮显示

原创|其它|编辑:郝浩|2012-09-17 14:39:53.000|阅读 2234 次

概述:为了突出某些特定的文本字段,我们经常会用到高亮显示的功能。下面,我们就通过一个具体的事例来对Aspose.Words的这一功能进行了解:

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

为了突出某些特定的文本字段,我们经常会用到高亮显示的功能。下面,我们就通过一个具体的事例来对Aspose.Words的这一功能进行了解:

在这个事例中,我们将要实现对文档中所有的"your document"设置高亮显示的格式。

原文本如下图:

Aspose.Words如何实现高亮显示

运行的具体代码如下:

C#

 using System;
using System.Text.RegularExpressions;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Reflection;

using Aspose.Words;

namespace FindAndHighlight
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Sample infrastructure.
            string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
            string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;
           
             Document doc = new Document(dataDir + "TestFile.doc");

            // We want the "your document" phrase to be highlighted.
            Regex regex = new Regex("your document", RegexOptions.IgnoreCase);
             doc.Range.Replace(regex, new ReplaceEvaluatorFindAndHighlight(), true);

            // Save the output document.
            doc.Save(dataDir + "TestFile Out.doc");
        }

        private class ReplaceEvaluatorFindAndHighlight : IReplacingCallback
        {
            /// <summary>
            /// This method is called by the Aspose.Words find and replace engine for each match.
            /// This method highlights the match string, even if it spans multiple runs.
            /// </summary>
            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 highlighting.
                 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 highlight all runs in the sequence.
                foreach (Run run in runs)
                     run.Font.HighlightColor = Color.Yellow;

                // Signal to the replace engine to do nothing because we have already done all what we wanted.
                return ReplaceAction.Skip;
            }
        }

        /// <summary>
        /// Splits text of the specified run into two runs.
        /// Inserts the new run just after the specified run.
        /// </summary>
        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, position);
            run.ParentNode.InsertAfter(afterRun, run);
            return afterRun;
        }
    }
}
 

 


Visual Basic

 Imports Microsoft.VisualBasic
Imports System
Imports System.Text.RegularExpressions
Imports System.Collections
Imports System.Drawing
Imports System.IO
Imports System.Reflection

Imports Aspose.Words

Namespace FindAndHighlight
    Friend Class Program
        Public Shared Sub Main(ByVal args() As String)
            ' Sample infrastructure.
            Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
             Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath

            Dim doc As New Document(dataDir & "TestFile.doc")

            ' We want the "your document" phrase to be highlighted.
            Dim regex As New Regex("your document", RegexOptions.IgnoreCase)
             doc.Range.Replace(regex, New ReplaceEvaluatorFindAndHighlight(), True)

            ' Save the output document.
            doc.Save(dataDir & "TestFile Out.doc")
         End Sub

        Private Class ReplaceEvaluatorFindAndHighlight
            Implements IReplacingCallback
            ''' <summary>
            ''' This method is called by the Aspose.Words find and replace engine for each match.
            ''' This method highlights the match string, even if it spans multiple runs.
            ''' </summary>
            Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
                ' This is a Run node that contains either the beginning or the complete match.
                 Dim currentNode As Node = 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 Then
                    currentNode = SplitRun(CType(currentNode, Run), e.MatchOffset)
                 End If

                ' This array is used to store all nodes of the match for further highlighting.
                 Dim runs As New ArrayList()

                ' Find all runs that contain parts of the match string.
                Dim remainingLength As Integer = e.Match.Value.Length
                Do While (remainingLength > 0) AndAlso (currentNode IsNot Nothing) AndAlso (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
                    Loop While (currentNode IsNot Nothing) AndAlso (currentNode.NodeType <> NodeType.Run)
                 Loop

                ' Split the last run that contains the match if there is any text left.
                If (currentNode IsNot Nothing) AndAlso (remainingLength > 0) Then
                    SplitRun(CType(currentNode, Run), remainingLength)
                    runs.Add(currentNode)
                 End If

                ' Now highlight all runs in the sequence.
                For Each run As Run In runs
                    run.Font.HighlightColor = Color.Yellow
                 Next run

                ' Signal to the replace engine to do nothing because we have already done all what we wanted.
                Return ReplaceAction.Skip
            End Function
         End Class

        ''' <summary>
        ''' Splits text of the specified run into two runs.
        ''' Inserts the new run just after the specified run.
        ''' </summary>
        Private Shared Function SplitRun(ByVal run As Run, ByVal position As Integer) As Run
            Dim afterRun As Run = CType(run.Clone(True), Run)
            afterRun.Text = run.Text.Substring(position)
            run.Text = run.Text.Substring(0, position)
            run.ParentNode.InsertAfter(afterRun, run)
            Return afterRun
        End Function
    End Class
End Namespace
 
The Result

代码运行后的效果图如下:

Aspose.Words如何实现高亮显示


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@dpuzeg.cn

文章转载自:慧都控件网

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP