Разделы и макет страницы

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

SautinSoft.Document изначально не хранит понятие страниц. Однако часто бывает необходимо сохранить информацию о странице или группе страниц при их настройке. Для этого существует понятие Section.

Section (Раздел) — это набор Block элементов, сгруппированных по концепции унифицированных свойств страницы и имеющих определенные верхние и нижние колонтитулы.

Вы можете найти узел Section в Document Tree Structure, чтобы понять его назначение.

Как Вы можете видеть на картинке, каждый Section представляет группу Block элементов (Paragraph, Table , TableOfEntries) имеющих тот же макет страницы. Нет понятия страницы, и мы не знаем количество страниц сразу после загрузки или создания документа:

Section (Раздел) — это набор Block элементов, сгруппированных по концепции унифицированных свойств страницы и имеющих определенные верхние и нижние колонтитулы.

 

SautinSoft.Document может разделять документ на страницы, этот процесс называется Pagination

Pagination - это процесс разделения документа на отдельные страницы.

Таким образом, после процесса разбивки на страницы Вы будете знать количество страниц в документе и где размещен конкретный контент. Это может быть полезно при создании приложения для просмотра документов, печати, растеризации и так далее.

После запуска Pagination:

Pagination - это процесс разделения документа на отдельные страницы.

Полный код

using System;
using SautinSoft.Document;

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

            Sections();
        }

		/// <summary>
        /// Creates a document with different sections.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/sections-and-page-layout.php
        /// </remarks>
        static void Sections()
        {
            string documentPath = @"Sections.docx";

            // Let's create a simple document with two Sections.
            DocumentCore dc = new DocumentCore();

            // First Section, A4 - Portrait.
            Section s1 = new Section(dc);
            s1.PageSetup.PaperType = PaperType.A4;
            s1.PageSetup.Orientation = Orientation.Portrait;
            dc.Sections.Add(s1);

            // Add some text into section 1.
            s1.Content.Start.Insert("Text in section 1", new CharacterFormat() { FontName = "Times New Roman", Size = 60.0 });

            // Second Section, Letter - Landscape.
            Section s2 = new Section(dc);
            s2.PageSetup.PaperType = PaperType.Letter;
            s2.PageSetup.Orientation = Orientation.Landscape;
            dc.Sections.Add(s2);

            // Add some text into section 2.
            s2.Content.Start.Insert("Text in section 2", new CharacterFormat() { FontName = "Arial", Size = 72.0, FontColor = new Color("DD55AA") });

            // Save our document into 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()
        Sections()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Creates a document with different sections.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/sections-and-page-layout.php
    ''' </remarks>
    Sub Sections()
        Dim documentPath As String = "Sections.docx"

        ' Let's create a simple document with two Sections.
        Dim dc As New DocumentCore()

        ' First Section, A4 - Portrait.
        Dim s1 As New Section(dc)
        s1.PageSetup.PaperType = PaperType.A4
        s1.PageSetup.Orientation = Orientation.Portrait
        dc.Sections.Add(s1)

        ' Add some text into section 1.
        s1.Content.Start.Insert("Text in section 1", New CharacterFormat() With {
                .FontName = "Times New Roman",
                .Size = 60.0
            })

        ' Second Section, Letter - Landscape.
        Dim s2 As New Section(dc)
        s2.PageSetup.PaperType = PaperType.Letter
        s2.PageSetup.Orientation = Orientation.Landscape
        dc.Sections.Add(s2)

        ' Add some text into section 2.
        s2.Content.Start.Insert("Text in section 2", New CharacterFormat() With {
                .FontName = "Arial",
                .Size = 72.0,
                .FontColor = New Color("DD55AA")
            })

        ' Save our document into 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. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.