Форматирование и стили

  1. Добавьте SautinSoft.Document из Nuget.
  2. Создайте новый документ с текстом.
  3. Создайте новый стиль символов.
  4. Примените стиль к тексту.

Стили делают документ более компактным за счет уменьшения количества повторяющихся определений и свойств, а также объема работы, необходимой для внесения изменений во внешний вид документа. Существует несколько типов стилей: CharacterStyle, ParagraphStyle, TableStyle и ListStyle.

Например, используя CharacterStyle, внешний вид всех фрагментов текста, которые используют общий стиль, можно изменить в одном месте, в определении этого стиля.

Полный код

using SautinSoft.Document;
using SautinSoft.Document.Drawing;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            FormattingAndStyles();
        }
        /// <summary>
        /// Creates a new document and applies formatting and styles.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/formatting-and-styles.php
        /// </remarks>
        static void FormattingAndStyles()
        {
            string docxPath = @"FormattingAndStyles.docx";

            // Let's create a new document.
            DocumentCore dc = new DocumentCore();            
            Run run1 = new Run(dc, "This is Run 1 with character format Green. ");
            Run run2 = new Run(dc, "This is Run 2 with style Red.");
            
            // Create a new character style.
            CharacterStyle redStyle = new CharacterStyle("Red");
            redStyle.CharacterFormat.FontColor = Color.Red;
            dc.Styles.Add(redStyle);
            
            // Apply the direct character formatting.            
            run1.CharacterFormat.FontColor = Color.DarkGreen;

            // Apply only the style.
            run2.CharacterFormat.Style = redStyle;
            
            dc.Content.End.Insert(run1.Content);
            dc.Content.End.Insert(run2.Content);

            // Save our document into DOCX format.
            dc.Save(docxPath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(docxPath) { UseShellExecute = true });
        }
    }
}

Download

Imports SautinSoft.Document
Imports SautinSoft.Document.Drawing

Namespace Example
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            FormattingAndStyles()
        End Sub
        ''' Get your free 30-day key here:   
        ''' https://sautinsoft.com/start-for-free/
        ''' <summary>
        ''' Creates a new document and applies formatting and styles.
        ''' </summary>
        ''' <remarks>
        ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/formatting-and-styles.php
        ''' </remarks>
        Private Shared Sub FormattingAndStyles()
            Dim docxPath As String = "FormattingAndStyles.docx"

            ' Let's create a new document.
            Dim dc As New DocumentCore()
            Dim run1 As New Run(dc, "This is Run 1 with character format Green. ")
            Dim run2 As New Run(dc, "This is Run 2 with style Red.")

            ' Create a new character style.
            Dim redStyle As New CharacterStyle("Red")
            redStyle.CharacterFormat.FontColor = Color.Red
            dc.Styles.Add(redStyle)

            ' Apply the direct character formatting.            
            run1.CharacterFormat.FontColor = Color.DarkGreen

            ' Apply only the style.
            run2.CharacterFormat.Style = redStyle

            dc.Content.End.Insert(run1.Content)
            dc.Content.End.Insert(run2.Content)

            ' Save our document into DOCX format.
            dc.Save(docxPath)

            ' Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(docxPath) With {.UseShellExecute = True})
        End Sub
    End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.