Использование DocumentBuilder для перемещения курсора в указанную позицию на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Создайте новый документ.
  3. Создайте Builder на основе документа.
  4. Для перемещения в любую позицию вызывайте методы MoveTo..., например, метод MoveToParagraph.

   Чтобы переместить курсор в документе, используйте метод DocumentBuilderMoveTo. Ниже приведены наиболее часто используемые методы перемещения.

   Для перехода к началу документа, вызовите метод DocumentBuilderMoveToDocumentStart. Если Вам нужно перейти в конец документа, вызовите DocumentBuilderMoveToDocumentEnd.
   Для перемещения данных в верхний или нижний колонтитулы используйте метод DocumentBuilderMoveToHeaderFooter.
   Используйте метод DocumentBuilderMoveToParagraph для перемещения курсора к нужному абзацу в текущем разделе.
   Используйте метод DocumentBuilderMoveToCell для перемещения курсора в ячейку таблицы в текущем разделе.
   Чтобы перейти к закладке, используйте метод DocumentBuilderMoveToBookmark. isStart при значении true перемещает курсор в начало закладки. При значении false перемещает курсор в конец закладки. isAfter, когда true, перемещает курсор после начальной или конечной позиции закладки. При значении false курсор перемещается перед начальной или конечной позицией закладки.

Полный код

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 30-day key here:   
            // https://sautinsoft.com/start-for-free/
            MovingCursor();
        }
        /// <summary>
        /// Moving the current cursor position in the document using DocumentBuilder.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-moving-cursor.php
        /// </remarks>

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

            db.MoveToHeaderFooter(HeaderFooterType.HeaderDefault);
            db.Writeln("Moved the cursor to the header and inserted this text.");

            db.MoveToDocumentStart();
            db.CharacterFormat.Size = 16;
            db.CharacterFormat.FontColor = Color.Blue;
            db.Writeln("Moved the cursor to the start of the document.");

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

            db.MoveToBookmark("Firstbookmark", true, false);
            db.Writeln("Moved the cursor to the start of the Bookmark.");

            db.CharacterFormat.FontColor = Color.Black;
            Field f1 = db.InsertField("DATE");
            db.MoveToField(f1, false);
            db.Write("Before the field");

            // Moving to the Header and insert the table with three cells.
            db.MoveToHeaderFooter(HeaderFooterType.HeaderDefault);
            db.StartTable();
            db.TableFormat.PreferredWidth = new TableWidth(LengthUnitConverter.Convert(6, LengthUnit.Inch, LengthUnit.Point), TableWidthUnit.Point);
            db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Green, 1);
            db.RowFormat.Height = new TableRowHeight(40, HeightRule.Exact);
            db.CharacterFormat.FontColor = Color.Green;
            db.CharacterFormat.Italic = false;
            db.InsertCell();
            db.Write("This is Row 1 Cell 1");
            db.InsertCell();
            db.Write("This is Row 1 Cell 2");
            db.InsertCell();
            db.Write("This is Row 1 Cell 3");
            db.EndTable();

            // Insert the text in the second cell in the sixth position.
            db.MoveToCell(0, 0, 1, 5);
            db.CharacterFormat.Size = 18;
            db.CharacterFormat.FontColor = Color.Orange;
            db.Write("InsertToCell");

            db.MoveToDocumentEnd();
            db.CharacterFormat.Size = 16;
            db.CharacterFormat.FontColor = Color.Blue;
            db.Writeln("Moved the cursor to the end of the document.");

            // Save our document into DOCX format.
            string resultPath = @"Result.docx";
            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
Imports SautinSoft.Document.Drawing
Imports SautinSoft.Document.Tables

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			MovingCursor()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' Moving the current cursor position in the document using DocumentBuilder.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-moving-cursor.php
		''' </remarks>

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

			db.MoveToHeaderFooter(HeaderFooterType.HeaderDefault)
			db.Writeln("Moved the cursor to the header and inserted this text.")

			db.MoveToDocumentStart()
			db.CharacterFormat.Size = 16
			db.CharacterFormat.FontColor = Color.Blue
			db.Writeln("Moved the cursor to the start of the document.")

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

			db.MoveToBookmark("Firstbookmark", True, False)
			db.Writeln("Moved the cursor to the start of the Bookmark.")

			db.CharacterFormat.FontColor = Color.Black
			Dim f1 As Field = db.InsertField("DATE")
			db.MoveToField(f1, False)
			db.Write("Before the field")

			' Moving to the Header and insert the table with three cells.
			db.MoveToHeaderFooter(HeaderFooterType.HeaderDefault)
			db.StartTable()
			db.TableFormat.PreferredWidth = New TableWidth(LengthUnitConverter.Convert(6, LengthUnit.Inch, LengthUnit.Point), TableWidthUnit.Point)
			db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Green, 1)
			db.RowFormat.Height = New TableRowHeight(40, HeightRule.Exact)
			db.CharacterFormat.FontColor = Color.Green
			db.CharacterFormat.Italic = False
			db.InsertCell()
			db.Write("This is Row 1 Cell 1")
			db.InsertCell()
			db.Write("This is Row 1 Cell 2")
			db.InsertCell()
			db.Write("This is Row 1 Cell 3")
			db.EndTable()

			' Insert the text in the second cell in the sixth position.
			db.MoveToCell(0, 0, 1, 5)
			db.CharacterFormat.Size = 18
			db.CharacterFormat.FontColor = Color.Orange
			db.Write("InsertToCell")

			db.MoveToDocumentEnd()
			db.CharacterFormat.Size = 16
			db.CharacterFormat.FontColor = Color.Blue
			db.Writeln("Moved the cursor to the end of the document.")

			' 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


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



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

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