Импортируйте элемент со стилями. Режим: UseDestinationStyles

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите исходный документ DOCX.
  3. Создайте новый документ.
  4. Импортируйте первый абзац из источника.

UseDestinationStyles означает копирование только тех стилей, которые не существуют в пункте назначения документ.
Если целевой документ уже содержит стиль с таким же именем, следовательно, стиль из источника скопирован не будет.

Например, целевой документ содержит стиль "Green" (FontSize = 24, DarkGreen).

Destination:

И исходный документ также содержит стиль с именем "Green" (FontSize = 20, Green, Underline).

Давайте импортируем 1-й абзац из исходного документа.
Абзац содержит текст "Shrek" выделенный стилем "Green".
Поскольку стиль с таким же названием уже существует, новый "Green" стиль импортирован не будет.

Source:

(SourceStyles.docx)

После импорта импортированное содержимое изменит свое форматирование в соответствии с "Green" стилем в документе назначения..
Потому что стиль "Green" (FontSize = 20, Green, Underline) не был импортирован.

Result:

Будьте осторожны с режимом UseDestinationStyles. Чтобы сохранить все стили и форматирование, мы советуем Вам использовать KeepDifferentStyles

Полный код

using SautinSoft.Document;
using SautinSoft.Document.Tables;
using System.Linq;

namespace Sample
{
    class Sample
    {

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

            ImportUseDestinationStyles();
        }

        /// <summary>
        /// Import an Element with Styles from another document. Mode: UseDestinationStyles.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/import-element-use-destination-styles.php
        /// </remarks>
        private static void ImportUseDestinationStyles()
        {
            // Mode: UseDestinationStyles.

            // 'UseDestinationStyles' means to copy only styles wchich are don't exist 
            // in the destination document. 
            // If the destination document already contains a style with the same name, 
            // therefore a style from a source will not be copied.

            // For example, a destination document contains a style "Green" (FontSize = 24, DarkGreen).
            // And a source document also contains a style with name "Green" (FontSize = 20, Green, Underline).
            // After the importing, the imported content will change its formatting correspondly to the "Green" style in the destination document.
            // Because style "Green" (FontSize = 20, Green, Underline) was not imported.

            DocumentCore source = DocumentCore.Load(@"..\..\..\SourceStyles.docx");
            DocumentCore dest = new DocumentCore();

            // Before importing a style from another document, let's create a style 
            // with the same name but different formatting to see 
            // how the name conflict will be resolved in mode 'UseDestinationStyles'.
            CharacterStyle chStyle = new CharacterStyle("Green");
            chStyle.CharacterFormat.FontColor = Color.DarkGreen;
            chStyle.CharacterFormat.Size = 24;
            dest.Styles.Add(chStyle);
            dest.Content.End.Insert(new Run(dest, "First ", new CharacterFormat() { Style = chStyle }).Content);
            
            // Create an ImportSession with mode 'UseDestinationStyles'.
            ImportSession session = new ImportSession(source, dest, StyleImportingMode.UseDestinationStyles);

            // Let's import a 1st paragraph from the source document.
            // The paragraph contains a text marked by style "Green". 
            // As a style with the same name is already exist, the new "Green" style will not be imported.
            Paragraph importedPar = dest.Import<Paragraph>((Paragraph)source.Sections[0].Blocks[0], true, session);
            dest.Content.End.Insert(importedPar.Content);                  

            // Save the destination document into DOCX format.
            string docPath = "UseDestinationStyles.docx";
            dest.Save(docPath);

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

Download

Imports SautinSoft.Document
Imports SautinSoft.Document.Tables
Imports System.Linq

Namespace Sample
    Friend Class Sample

        Shared Sub Main(ByVal args() As String)
            ImportUseDestinationStyles()
        End Sub
        ''' Get your free 30-day key here:   
        ''' https://sautinsoft.com/start-for-free/
        ''' <summary>
        ''' Import an Element with Styles from another document. Mode: UseDestinationStyles.
        ''' </summary>
        ''' <remarks>
        ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/import-element-use-destination-styles.php
        ''' </remarks>
        Private Shared Sub ImportUseDestinationStyles()
            ' Mode: UseDestinationStyles.

            ' 'UseDestinationStyles' means to copy only styles wchich are don't exist 
            ' in the destination document. 
            ' If the destination document already contains a style with the same name, 
            ' therefore a style from a source will not be copied.

            ' For example, a destination document contains a style "Green" (FontSize = 24, DarkGreen).
            ' And a source document also contains a style with name "Green" (FontSize = 20, Green, Underline).
            ' After the importing, the imported content will change its formatting correspondly to the "Green" style in the destination document.
            ' Because style "Green" (FontSize = 20, Green, Underline) will not be imported.

            Dim source As DocumentCore = DocumentCore.Load("..\..\..\SourceStyles.docx")
            Dim dest As New DocumentCore()

            ' Before importing a style from another document, let's create a style 
            ' with the same name but different formatting to see 
            ' how the name conflict will be resolved in mode 'UseDestinationStyles'.
            Dim chStyle As New CharacterStyle("Green")
            chStyle.CharacterFormat.FontColor = Color.DarkGreen
            chStyle.CharacterFormat.Size = 24
            dest.Styles.Add(chStyle)
            dest.Content.End.Insert((New Run(dest, "First ", New CharacterFormat() With {.Style = chStyle})).Content)

            ' Create an ImportSession with mode 'UseDestinationStyles'.
            Dim session As New ImportSession(source, dest, StyleImportingMode.UseDestinationStyles)

            ' Let's import a 1st paragraph from the source document.
            ' The paragraph contains a text marked by style "Green". 
            ' As a style with the same name is already exist, the new "Green" style will not be imported.
            Dim importedPar As Paragraph = dest.Import(Of Paragraph)(CType(source.Sections(0).Blocks(0), Paragraph), True, session)
            dest.Content.End.Insert(importedPar.Content)

            ' Save the destination document into DOCX format.
            Dim docPath As String = "UseDestinationStyles.docx"
            dest.Save(docPath)

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

Download


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



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

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