Работа с текстом (встроенные производные элементы)

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

В SautinSoft.Document библиотеке любой текст представлен коллекцией Inline-полученный объекты: Run , SpecialCharacter , Hyperlink, Field и т.д.

Самый популярный текстовый элемент - Run.

Run (Inline derived) представляет собой контейнер для одного или нескольких текстовых символов, имеющих одинаковое символьное форматирование.

Чтобы понять, как организован текст, давайте рассмотрим простой Paragraph :

Rich Formatted text

На самом деле, наш Paragraph содержит 4 встроенных производных элемента:

  • 1 - Run, зеленый текст: "This is a rich".
  • 2 - Run, синий текст: " formatted text".
  • 3 - SpecialCharacter, тип: LineBreak.
  • 4 - Run, черный текст: "with a line break.".

Все эти элементы являются Inline-выведенный и расположенный внутри InlineCollection из Paragraph.

Смотрите Document Tree Structure что бы понимать иерархию и взаимосвязи между элементами.

Чтобы проиллюстрировать работу с текстом, давайте создадим такой же документ, как на картинке:

Основные шаги

  1. Обратите внимание, что Вы импортируете пространство имен SautinSoft.Document.
    using SautinSoft.Document;
  2. Прежде всего, давайте создадим экземпляр DocumentCore с именем dc.
    
    DocumentCore dc = new DocumentCore();
    
    DocumentCore является корневым классом, он представляет сам документ.
  3. Добавить новый Section в наш документ.
    
        Section section = new Section(dc);
        dc.Sections.Add(section);
    
    Section (Раздел) — это набор Block элементов, сгруппированных по концепции унифицированных свойств страницы и имеющих определенные верхние и нижние колонтитулы.
  4. Создайте новый Paragraph элемент и добавляем наш текст, используя Run и SpecialCharacter:
                // Create a new paragraph and add into the section.
                Paragraph par = new Paragraph(dc);
                section.Blocks.Add(par);
    
                // Create Inline-derived objects with text.
                Run run1 = new Run(dc, "This is a rich");
                run1.CharacterFormat = new CharacterFormat() { FontName = "Times New Roman", Size = 18.0, FontColor = new Color(112, 173, 71) };
    
                Run run2 = new Run(dc, " formatted text");
                run2.CharacterFormat = new CharacterFormat(){ FontName = "Arial", Size = 10.0, FontColor = new Color("#0070C0") };
    
                SpecialCharacter spch3 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak);
    
                Run run4 = new Run(dc, "with a line break.");
                run4.CharacterFormat = new CharacterFormat() { FontName = "Times New Roman", Size = 10.0, FontColor = Color.Black };
    
                // Add our inlines into the paragraph.
                par.Inlines.Add(run1);
                par.Inlines.Add(run2);
                par.Inlines.Add(spch3);
                par.Inlines.Add(run4);
        

Мы также предлагаем вам другой способ вставьте текст внутрь документа, используя диапазон содержимого объект

Полный код

using SautinSoft.Document;

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

            AddText();
        }

        /// <summary>
        /// How to create a simple document with text. 
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/text.php
        /// </remarks>
        public static void AddText()
        {
            string documentPath = @"Text.docx";

            // Let's create a new document.
            DocumentCore dc = new DocumentCore();

            // Create a new section and add into the document.
            Section section = new Section(dc);
            dc.Sections.Add(section);

            // Create a new paragraph and add into the section.
            Paragraph par = new Paragraph(dc);
            section.Blocks.Add(par);

            // Create Inline-derived objects with text.
            Run run1 = new Run(dc, "This is a rich");
            run1.CharacterFormat = new CharacterFormat() { FontName = "Times New Roman", Size = 18.0, FontColor = new Color(112, 173, 71) };

            Run run2 = new Run(dc, " formatted text");
            run2.CharacterFormat = new CharacterFormat() { FontName = "Arial", Size = 10.0, FontColor = new Color("#0070C0") };

            SpecialCharacter spch3 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak);

            Run run4 = new Run(dc, "with a line break.");
            run4.CharacterFormat = new CharacterFormat() { FontName = "Times New Roman", Size = 10.0, FontColor = Color.Black };

            // Add our inlines into the paragraph.
            par.Inlines.Add(run1);
            par.Inlines.Add(run2);
            par.Inlines.Add(spch3);
            par.Inlines.Add(run4);

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

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

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Module Sample
    Sub Main()
        AddText()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' How to create a simple document with text. 
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/text.php
    ''' </remarks>
    Sub AddText()
        Dim documentPath As String = "Text.docx"

        ' Let's create a new document.
        Dim dc As New DocumentCore()

        ' Create a new section and add into the document.
        Dim section As New Section(dc)
        dc.Sections.Add(section)

        ' Create a new paragraph and add into the section.
        Dim par As New Paragraph(dc)
        section.Blocks.Add(par)

        ' Create Inline-derived objects with text.
        Dim run1 As New Run(dc, "This is a rich")
        run1.CharacterFormat = New CharacterFormat() With {
            .FontName = "Times New Roman",
            .Size = 18.0,
            .FontColor = New Color(112, 173, 71)
        }

        Dim run2 As New Run(dc, " formatted text")
        run2.CharacterFormat = New CharacterFormat() With {
            .FontName = "Arial",
            .Size = 10.0,
            .FontColor = New Color("#0070C0")
        }

        Dim spch3 As New SpecialCharacter(dc, SpecialCharacterType.LineBreak)

        Dim run4 As New Run(dc, "with a line break.")
        run4.CharacterFormat = New CharacterFormat() With {
            .FontName = "Times New Roman",
            .Size = 10.0,
            .FontColor = Color.Black
        }

        ' Add our inlines into the paragraph.
        par.Inlines.Add(run1)
        par.Inlines.Add(run2)
        par.Inlines.Add(spch3)
        par.Inlines.Add(run4)

        ' Save our document into the DOCX format.
        dc.Save(documentPath)

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

Download


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



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

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