Создать документ


SautinSoft.Document поддерживает форматы:

PDF DOCX RTF HTML Текст Изображения
Create/Read/Write Create/Read/Write Create/Read/Write Create/Read/Write Create/Read/Write Create/Read(OCR)/Write

Давайте создадим простой документ с текстом "Hello World!":

Здесь мы покажем Вам, как создать такой же документ с нуля тремя способами:

  • Используя DocumentBuilder (Wizard)
  • Используя DOM (Объектная модель документа) напрямую.
  • Используя DOM и ContentRange класс.

Полный код

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/

            // You can create the same document by using 3 ways:
            //
            //  + DocumentBuilder
            //  + DOM directly
            //  + DOM and ContentRange
            //
            // Choose any of them which you like.

            // Way 1:
            CreateUsingDocumentBuilder();

            // Way 2:
            CreateUsingDOM();

            // Way 3:
            CreateUsingContentRange();
        }

        /// <summary>
        /// Creates a new document using DocumentBuilder and saves it in a desired format.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/create-document.php
        /// </remarks>
        static void CreateUsingDocumentBuilder()
        {
            // Create a new document and DocumentBuilder.
            DocumentCore dc = new DocumentCore();
            DocumentBuilder db = new DocumentBuilder(dc);

            // Specify the formatting and insert text.
            db.CharacterFormat.FontName = "Verdana";
            db.CharacterFormat.Size = 65.5f;
            db.CharacterFormat.FontColor = Color.Orange;
            db.Write("Hello World!");

            // Save the document in DOCX format.
            string outFile = "DocumentBuilder.docx";
            dc.Save(outFile);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
        /// <summary>
        /// Creates a new document using DOM and saves it in a desired format.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/create-document.php
        /// </remarks>
        static void CreateUsingDOM()
        {
            // Create a new document.
            DocumentCore dc = new DocumentCore();

            // Create a new section,
            // add the section the document.
            Section sect = new Section(dc);
            dc.Sections.Add(sect);

            // Create a new paragraph,
            // add the paragraph to the section.
            Paragraph par = new Paragraph(dc);
            sect.Blocks.Add(par);

            // Create a new run (text object),
            // add the run to the paragraph.
            Run run = new Run(dc, "Hello World!");
            run.CharacterFormat.FontName = "Verdana";
            run.CharacterFormat.Size = 65.5f;
            run.CharacterFormat.FontColor = Color.Orange;
            par.Inlines.Add(run);

            // Save the document in PDF format.
            string outFile = @"DOM.pdf";
            dc.Save(outFile);

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


        /// <summary>
        /// Creates a new document using DOM and ContentRange and saves it in a desired format.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/create-document.php
        /// </remarks>
        static void CreateUsingContentRange()
        {
            // Create a new document.
            DocumentCore dc = new DocumentCore();
            // Insert the formatted text into the document.
            dc.Content.End.Insert("Hello World!", new CharacterFormat() { FontName = "Verdana", Size = 65.5f, FontColor = Color.Orange });

            // Save the document in HTML format.
            string outFile = @"ContentRange.html";
            dc.Save(outFile, new HtmlFixedSaveOptions() { Title = "ContentRange" });

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

Download

Imports SautinSoft.Document

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' You can create the same document by using 3 ways:
			'
			'  + DocumentBuilder
			'  + DOM directly
			'  + DOM and ContentRange
			'
			' Choose any of them which you like.

			' Way 1:
			CreateUsingDocumentBuilder()

			' Way 2:
			CreateUsingDOM()

			' Way 3:
			CreateUsingContentRange()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/

		''' <summary>
		''' Creates a new document using DocumentBuilder and saves it in a desired format.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/create-document.php
		''' </remarks>
		Private Shared Sub CreateUsingDocumentBuilder()
			' Create a new document and DocumentBuilder.
			Dim dc As New DocumentCore()
			Dim db As New DocumentBuilder(dc)

			' Specify the formatting and insert text.
			db.CharacterFormat.FontName = "Verdana"
			db.CharacterFormat.Size = 65.5F
			db.CharacterFormat.FontColor = Color.Orange
			db.Write("Hello World!")

			' Save the document in DOCX format.
			Dim outFile As String = "DocumentBuilder.docx"
			dc.Save(outFile)

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
		''' <summary>
		''' Creates a new document using DOM and saves it in a desired format.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/create-document.php
		''' </remarks>
		Private Shared Sub CreateUsingDOM()
			' Create a new document.
			Dim dc As New DocumentCore()

			' Create a new section,
			' add the section the document.
			Dim sect As New Section(dc)
			dc.Sections.Add(sect)

			' Create a new paragraph,
			' add the paragraph to the section.
			Dim par As New Paragraph(dc)
			sect.Blocks.Add(par)

			' Create a new run (text object),
			' add the run to the paragraph.
			Dim run As New Run(dc, "Hello World!")
			run.CharacterFormat.FontName = "Verdana"
			run.CharacterFormat.Size = 65.5F
			run.CharacterFormat.FontColor = Color.Orange
			par.Inlines.Add(run)

			' Save the document in PDF format.
			Dim outFile As String = "DOM.pdf"
			dc.Save(outFile)

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


		''' <summary>
		''' Creates a new document using DOM and ContentRange and saves it in a desired format.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/create-document.php
		''' </remarks>
		Private Shared Sub CreateUsingContentRange()
			' Create a new document.
			Dim dc As New DocumentCore()
			' Insert the formatted text into the document.
			dc.Content.End.Insert("Hello World!", New CharacterFormat() With {
				.FontName = "Verdana",
				.Size = 65.5F,
				.FontColor = Color.Orange
			})

			' Save the document in HTML format.
			Dim outFile As String = "ContentRange.html"
			dc.Save(outFile, New HtmlFixedSaveOptions() With {.Title = "ContentRange"})

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

Download


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



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

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