Использование DocumentBuilder для сохранения и извлечения текущего форматирования символов в стеке на C# и .NET

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

   Для сохранения текущего форматирования символов в стеке, используйте метод DocumentBuilderPushCharacterFormat. Чтобы извлечь форматирование символов, ранее сохраненное в стеке, используйте метод DocumentBuilderPopCharacterFormat.

Полный код

using System;
using SautinSoft.Document;
using System.Text;
using SautinSoft.Document.Drawing;
using SautinSoft.Document.Tables;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 100-day key here:   
            // https://sautinsoft.com/start-for-free/
            FormattingOnStack();
        }
        /// <summary>
        /// Saves and retrieves current character formatting on the stack.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/character-formatting-stack.php
        /// </remarks>

        static void FormattingOnStack()
        {
            DocumentCore dc = new DocumentCore();
            DocumentBuilder db = new DocumentBuilder(dc);

            db.CharacterFormat.FontName = "Arial";
            db.CharacterFormat.Size = 16;
            db.CharacterFormat.FontColor = Color.Blue;
            db.Writeln("This text contains formatting font name, size and color. Save the character formatting of this text in as first element of the stack.");
            db.PushCharacterFormat();
            db.CharacterFormat.ClearFormatting();

            db.CharacterFormat.Size = 26;
            db.CharacterFormat.FontColor = Color.Orange;
            db.CharacterFormat.Italic = true;
            db.Writeln("This text contains formatting for font size, color and italic. Save the character formatting of this text as second element of the stack.");
            db.PushCharacterFormat();
            db.CharacterFormat.ClearFormatting();

            // Insert the third way the character formatting of the text.
            db.CharacterFormat.Size = 14;
            db.CharacterFormat.FontColor = Color.Red;
            db.CharacterFormat.Bold = true;
            db.Writeln("This text contains formatting for font size, color and bold.");
            db.CharacterFormat.ClearFormatting();

            // Retrieves text character formatting from the stack (the second element).
            db.PopCharacterFormat();

            // Retrieves text character formatting from the stack (the first element).
            db.PopCharacterFormat();
            db.Writeln("The character formatting of this text is extracted from the stack as first element.");

            // Save our document into DOCX format.
            string resultPath = @"Result.docx";
            dc.Save(resultPath, new DocxSaveOptions());
			
			// Important for Linux: Install MS Fonts
			// sudo apt install ttf-mscorefonts-installer -y

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

Download

Imports System
Imports SautinSoft.Document
Imports System.Text
Imports SautinSoft.Document.Drawing
Imports SautinSoft.Document.Tables

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			FormattingOnStack()
		End Sub
                ''' Get your free 100-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' Saves and retrieves current character formatting on the stack.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/character-formatting-stack.php
		''' </remarks>

		Private Shared Sub FormattingOnStack()
			Dim dc As New DocumentCore()
			Dim db As New DocumentBuilder(dc)

			db.CharacterFormat.FontName = "Arial"
			db.CharacterFormat.Size = 16
			db.CharacterFormat.FontColor = Color.Blue
			db.Writeln("This text contains formatting font name, size and color. Save the character formatting of this text in as first element of the stack.")
			db.PushCharacterFormat()
			db.CharacterFormat.ClearFormatting()

			db.CharacterFormat.Size = 26
			db.CharacterFormat.FontColor = Color.Orange
			db.CharacterFormat.Italic = True
			db.Writeln("This text contains formatting for font size, color and italic. Save the character formatting of this text as second element of the stack.")
			db.PushCharacterFormat()
			db.CharacterFormat.ClearFormatting()

			' Insert the third way the character formatting of the text.
			db.CharacterFormat.Size = 14
			db.CharacterFormat.FontColor = Color.Red
			db.CharacterFormat.Bold = True
			db.Writeln("This text contains formatting for font size, color and bold.")
			db.CharacterFormat.ClearFormatting()

			' Retrieves text character formatting from the stack (the second element).
			db.PopCharacterFormat()

			' Retrieves text character formatting from the stack (the first element).
			db.PopCharacterFormat()
			db.Writeln("The character formatting of this text is extracted from the stack as first element.")

			' Save our document into DOCX format.
			Dim resultPath As String = "result.docx"
			dc.Save(resultPath, New DocxSaveOptions())

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

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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