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

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

   Используйте коды полей для вставки полей, которые могут предоставлять автоматически обновляемую информацию, такую как время, заголовок, номера страниц и так далее. Вы можете переключаться между отображением кодов полей и результатов в документе в Microsoft Word с помощью сочетания клавиш Alt + F9. Коды полей отображаются между фигурными скобками { }. Используйте DocumentBuilderInsertField для создания полей в документе.

   Чтобы создать форму в Microsoft Word, которую могут заполнять другие пользователи, начните с шаблона или документа и добавьте элементы управления содержимым. Элементы управления содержимым включают в себя такие элементы, как флажки, текстовые поля, средства выбора даты и выпадающие списки. DocumentBuilder предоставляет специальные методы для вставки каждого типа полей формы в документ: DocumentBuilderInsertTextInput, DocumentBuilderInsertCheckBox, DocumentBuilderInsertComboBox.

Полный код

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/
            InsertingField();
        }
        /// <summary>
        /// Generate document with forms and fields using DocumentBuilder.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-inserting-field.php
        /// </remarks>

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

            string resultPath = @"Result.pdf";
            string[] items = { "One", "Two", "Three", "Four", "Five" };

            // Insert the formatted text into the document using DocumentBuilder.
            db.CharacterFormat.FontName = "Verdana";
            db.CharacterFormat.Size = 16;
            db.CharacterFormat.FontColor = Color.Orange;
            db.Writeln("Generate document with forms and fields using DocumentBuilder.");
            db.CharacterFormat.ClearFormatting();

            db.Write(@"{ TIME   \* MERGEFORMAT } - ");
            db.InsertField("TIME");
            db.InsertSpecialCharacter(SpecialCharacterType.LineBreak);

            db.InsertTextInput("TextInput", FormTextType.RegularText, "", "Insert Text Input", 0);
            db.InsertSpecialCharacter(SpecialCharacterType.LineBreak);
            
            db.InsertCheckBox("CheckBox", true, 0);
            db.InsertSpecialCharacter(SpecialCharacterType.LineBreak);

            db.InsertComboBox("DropDown", items, 3);

            // Save our document into PDF format.
            dc.Save(resultPath, new PdfSaveOptions());

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

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			InsertingField()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' Generate document with forms and fields using DocumentBuilder.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-inserting-field.php
		''' </remarks>

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

			Dim resultPath As String = "result.pdf"
			Dim items() As String = {"One", "Two", "Three", "Four", "Five"}

			' Insert the formatted text into the document using DocumentBuilder.
			db.CharacterFormat.FontName = "Verdana"
			db.CharacterFormat.Size = 16
			db.CharacterFormat.FontColor = Color.Orange
			db.Writeln("Generate document with forms and fields using DocumentBuilder.")
			db.CharacterFormat.ClearFormatting()

			db.Write("{ TIME   \* MERGEFORMAT } - ")
			db.InsertField("TIME")
			db.InsertSpecialCharacter(SpecialCharacterType.LineBreak)

			db.InsertTextInput("TextInput", FormTextType.RegularText, "", "Insert Text Input", 0)
			db.InsertSpecialCharacter(SpecialCharacterType.LineBreak)

			db.InsertCheckBox("CheckBox", True, 0)
			db.InsertSpecialCharacter(SpecialCharacterType.LineBreak)

			db.InsertComboBox("DropDown", items, 3)

			' Save our document into PDF format.
			dc.Save(resultPath, New PdfSaveOptions())

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