Использование DocumentBuilder для вставки закладки на C# и .NET

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

   Закладки работают с гиперссылками, чтобы Вы могли перейти к определенному месту в документе.

   Чтобы вставить закладку в документ, вызовите DocumentBuilderStartBookmark, передав ему нужное имя закладки. Вставьте содержимое закладки, используя методы DocumentBuilder. Вызовите DocumentBuilderEndBookmark, передав ему то же имя, которое Вы использовали с DocumentBuilderStartBookmark. Имена закладок должны начинаться с буквы. Они могут включать как цифры, так и буквы, но не пробелы.

Полный код

using System;
using SautinSoft.Document;
using System.Text;
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/
            InsertingBookmark();
        }
        /// <summary>
        /// How to insert a Bookmark in a document using DocumentBuilder.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-inserting-bookmark.php
        /// </remarks>

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

            string resultPath = @"Result.docx";

            // Insert the formatted text into the document using DocumentBuilder.
            db.CharacterFormat.FontName = "Verdana";
            db.CharacterFormat.Size = 16;
            db.CharacterFormat.FontColor = Color.Orange;
            db.Writeln("This text is inserted by the DocumentBuilder.Write method with formatting.");

            // Marks the current position in the document as a 1st bookmark start.
            db.StartBookmark("Firstbookmark");
            db.CharacterFormat.Italic = true;
            db.CharacterFormat.Size = 12;
            db.CharacterFormat.FontColor = Color.Blue;
            db.Writeln("The text inside the bookmark 'Firstbookmark' is inserted by the DocumentBuilder.Writeln method.");
            
            // Marks the current position in the document as a 1st bookmark end.
            db.EndBookmark("Firstbookmark");

            // Insert text after the 1st bookmark.
            db.CharacterFormat.Italic = false;
            db.CharacterFormat.Size = 16;
            db.CharacterFormat.FontColor = Color.Orange;
            db.Writeln("DocumentBuilder.EndBookmark method with the same name points to the end of the bookmark.");

            // Marks the current position in the document as a 2nd bookmark start.
            db.StartBookmark("Secondbookmark");
            db.CharacterFormat.Italic = true;
            db.CharacterFormat.Size = 12;
            db.CharacterFormat.FontColor = Color.Blue;
            db.Writeln("Incorrectly spelled bookmarks or bookmarks with duplicate names will be ignored when saving the document.");

            // Marks the current position in the document as a 2nd bookmark end.
            db.EndBookmark("Secondbookmark");

            // Save our document into DOCX format.
            dc.Save(resultPath, new DocxSaveOptions());

            // 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

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			InsertingBookmark()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' How to insert a Bookmark in a document using DocumentBuilder.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-inserting-bookmark.php
		''' </remarks>

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

			Dim resultPath As String = "result.docx"

			' Insert the formatted text into the document using DocumentBuilder.
			db.CharacterFormat.FontName = "Verdana"
			db.CharacterFormat.Size = 16
			db.CharacterFormat.FontColor = Color.Orange
			db.Writeln("This text is inserted by the DocumentBuilder.Write method with formatting.")

			' Marks the current position in the document as a 1st bookmark start.
			db.StartBookmark("Firstbookmark")
			db.CharacterFormat.Italic = True
			db.CharacterFormat.Size = 12
			db.CharacterFormat.FontColor = Color.Blue
			db.Writeln("The text inside the bookmark 'Firstbookmark' is inserted by the DocumentBuilder.Writeln method.")

			' Marks the current position in the document as a 1st bookmark end.
			db.EndBookmark("Firstbookmark")

			' Insert text after the 1st bookmark.
			db.CharacterFormat.Italic = False
			db.CharacterFormat.Size = 16
			db.CharacterFormat.FontColor = Color.Orange
			db.Writeln("DocumentBuilder.EndBookmark method with the same name points to the end of the bookmark.")

			' Marks the current position in the document as a 2nd bookmark start.
			db.StartBookmark("Secondbookmark")
			db.CharacterFormat.Italic = True
			db.CharacterFormat.Size = 12
			db.CharacterFormat.FontColor = Color.Blue
			db.Writeln("Incorrectly spelled bookmarks or bookmarks with duplicate names will be ignored when saving the document.")

			' Marks the current position in the document as a 2nd bookmark end.
			db.EndBookmark("Secondbookmark")

			' Save our document into DOCX format.
			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


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



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

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