# Creating Documents

> Create documents in a WPF window: clear the TextControl, set page size in 1/96 inch, insert formatted text, combine files, store properties, use IsUndoEnabled.

- **Product:** TX Text Control .NET for WPF
- **Section:** Documentation
- **Kind:** Topic
- **Path:** TX Text Control .NET for WPF > Document Processing > Creating Documents
- **3713 words**
- **Web URL:** https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/creating/
- **LLMs URL:** https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/creating/llms.txt
- **LLMs-Full URL:** https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/creating/llms-full.txt

---

Letters, invoices and reports that a WPF application writes itself begin as an empty document, either in the `TextControl` of the window or in a `ServerTextControl` that the user never sees. Your code clears the editor for a new document, sets the page format, assembles text, HTML snippets and whole files, stores the document properties and switches off the undo history while it builds large documents.

The first steps are in [Create a Document Programmatically](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/getting-started/document-processing/create/llms-full.txt), which inserts formatted text, a table, an image and a header. [Document Object Model](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/object-model/llms-full.txt) explains how a document is organized. Each example below is the `Click` handler of a button in *MainWindow.xaml*, such as `<Button Content="New" Click="NewButton_Click" />`, next to a `TextControl` named `textControl1`. *MainWindow.xaml.cs* needs these `using` directives:

```csharp
using System.Windows;
using TXTextControl;
```

### Start a New Document

[ResetContents](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/resetcontents-method/llms-full.txt) deletes the entire contents of the `TextControl`. The page size and margins are settings of the control and stay as they are, so assign new values when a new document should start with the defaults:

```csharp
private void NewButton_Click(object sender, RoutedEventArgs e)
{
    // Remove the contents and start with US letter pages and 1-inch margins
    textControl1.ResetContents();
    textControl1.PageSize = new PageSize();
    textControl1.PageMargins = new PageMargins();
}
```

The [PageSize](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/pagesize/constructor/llms-full.txt) constructor without parameters creates US letter pages (8.5 x 11 inches), and the [PageMargins](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/pagemargins/constructor/llms-full.txt) constructor without parameters creates margins of 1 inch. Unlike the Windows Forms control, `WPF.TextControl` has no `ResetPageSize` and `ResetPageMargins` methods. How to ask the user before unsaved changes are lost is shown in [Load and Save Documents](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/getting-started/document-editor/load-save/llms-full.txt).

A [ServerTextControl](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/servertextcontrol/llms-full.txt) begins with an empty document. [Create](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/servertextcontrol/create-method/llms-full.txt) must be called before any other member and returns `false` when the instance couldn't be initialized; a `using` statement disposes it afterward. [Using ServerTextControl in Desktop Applications](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/servertextcontrol/llms-full.txt) describes the lifecycle.

### Set the Page Format

In WPF, [PageSize](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/pagesize-property/llms-full.txt) and [PageMargins](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/pagemargins-property/llms-full.txt) are measured in device-independent units of 1/96 inch by default, the unit of [PageUnit](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/pageunit-property/llms-full.txt). The following handler shows the current format and then sets margins of half an inch and landscape pages:

```csharp
private void PageFormatButton_Click(object sender, RoutedEventArgs e)
{
    // Values in 1/96 inch, the default PageUnit of WPF
    MessageBox.Show($"Page size: {textControl1.PageSize.Width} x {textControl1.PageSize.Height}\r\n" +
        $"Margins: {textControl1.PageMargins.Left}, {textControl1.PageMargins.Top}, " +
        $"{textControl1.PageMargins.Right}, {textControl1.PageMargins.Bottom}");

    // Margins of 0.5 inch (48/96 inch) on every side and landscape orientation
    textControl1.PageMargins = new PageMargins(48, 48, 48, 48);
    textControl1.Landscape = true;
}
```

The `PageMargins` constructor takes the left, top, right and bottom margin in the current unit, and [Landscape](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/landscape-property/llms-full.txt) turns the pages. `PageUnit` also offers millimeters, 1/100 inch and twips. A `ServerTextControl` has the same properties. Parts of a document that need their own page format, such as one landscape page in a portrait report, go into sections of their own, which [Sections, Pages, Headers, and Footers](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/sections-headers/llms-full.txt) describes.

### Build a Document From Pieces

The following handler writes a heading and a paragraph with a placeholder, appends an HTML snippet and then puts the contents of the file *terms.docx* where the placeholder was:

```csharp
private void BuildButton_Click(object sender, RoutedEventArgs e)
{
    textControl1.ResetContents();

    // Prepare text and formatting in a Selection object, then insert it in one step
    textControl1.Selection = new Selection()
    {
        Text = "Invoice INV-2025-001\r\n",
        FontName = "Arial",
        FontSize = 480, // 24 pt
        Bold = true
    };

    textControl1.Selection = new Selection()
    {
        Text = "Terms: [TERMS]\r\n",
        FontName = "Arial",
        FontSize = 240 // 12 pt
    };

    // Append an HTML snippet in a new paragraph at the end of the document
    textControl1.Append("<p>Thank you for your <strong>order</strong>.</p>",
        StringStreamType.HTMLFormat,
        AppendSettings.StartWithNewParagraph);

    // Replace a placeholder with the contents of another document
    const string placeholder = "[TERMS]";
    int position = textControl1.Find(placeholder, 0, FindOptions.NoMessageBox);

    if (position >= 0)
    {
        textControl1.Select(position, placeholder.Length);
        textControl1.Selection.Load("terms.docx", StreamType.WordprocessingML);
    }
}
```

The code works as follows:

- A new [Selection](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/selection/llms-full.txt) object carries text and attributes. Assigning it to `textControl1.Selection` inserts both at the input position in one step. The blog article [Speed Up Document Generation by Factor 2 Using Selection Objects in .NET C#](https://www.textcontrol.com/blog/2026/07/17/speed-up-document-generation-selection-objects-dotnet-csharp/) measures how much faster this is than formatting text after inserting it, using `ServerTextControl`.
- [Append](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/append-method/llms-full.txt) adds a document from a file, a byte array or a string to the end. `StringStreamType.HTMLFormat` reads the string as HTML.
- [Find](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/find-method/llms-full.txt) returns the zero-based position of the text, or -1. The search starts at position 0, and [FindOptions](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/findoptions/enumeration/llms-full.txt) `NoMessageBox` suppresses the message boxes of the editor.
- [Select](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/select-method/llms-full.txt) selects the placeholder, and [Selection.Load](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/selection/load-method/llms-full.txt) replaces the selected text with the loaded document, or inserts it at the input position when nothing is selected.

`Find` searches only the text part with the input focus: while the cursor is in a header, the placeholder in the main text isn't found. [Document Object Model](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/object-model/#the-input-focus-decides-what-a-collection-contains) describes why.

`Append` takes a value of [AppendSettings](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/appendsettings/enumeration/llms-full.txt) as its last parameter:

| Value | The appended document starts |
|---|---|
| `None` | At the end of the last paragraph |
| `StartWithNewParagraph` | In a new paragraph at the end of the document |
| `StartWithNewSection` | In a new section at the end of the document |

### Combine Several Documents

Load the first file and append the others to put a cover page and several chapters into one document. Done in a `ServerTextControl`, the intermediate steps stay invisible, and the window shows only the result:

```csharp
private void CombineButton_Click(object sender, RoutedEventArgs e)
{
    string[] files = { "cover.docx", "chapter1.docx", "chapter2.docx" };
    byte[] document;

    using (ServerTextControl tx = new ServerTextControl())
    {
        // Initialize the new instance before using it
        if (!tx.Create())
        {
            MessageBox.Show("ServerTextControl could not be initialized.");
            return;
        }

        // The first document replaces the empty contents
        tx.Load(files[0], StreamType.WordprocessingML);

        // Every further document is appended in a new section
        for (int i = 1; i < files.Length; i++)
        {
            tx.Append(files[i], StreamType.WordprocessingML, AppendSettings.StartWithNewSection);
        }

        tx.Save(out document, BinaryStreamType.InternalUnicodeFormat);
    }

    // Show the combined document in the editor
    textControl1.Load(document, BinaryStreamType.InternalUnicodeFormat);
    MessageBox.Show($"Sections: {textControl1.Sections.Count}, pages: {textControl1.Pages}");
}
```

The code works as follows:

- [ServerTextControl.Load](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/servertextcontrol/load-method/llms-full.txt) replaces the empty contents with the first file. [ServerTextControl.Append](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/servertextcontrol/append-method/llms-full.txt) adds every other file in a new section, which keeps its page format.
- [ServerTextControl.Save](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/servertextcontrol/save-method/llms-full.txt) writes the result to a byte array in the TX Text Control format, and [Load](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/load-method/llms-full.txt) of the `TextControl` shows it.

A document stored in a database is appended from its bytes, for example `tx.Append(bytes, BinaryStreamType.WordprocessingML, AppendSettings.StartWithNewSection);`. [Loading Documents](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/loading/llms-full.txt) compares `Load`, `Append` and `Selection.Load`.

### Store Document Properties

[DocumentSettings](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/documentsettings-property/llms-full.txt) holds general information about the document, such as its title, author, subject and keywords, and saving stores these values with the document. Set them before your code saves a generated document, as [Set the Properties in Code](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-editor/properties/#set-the-properties-in-code) in Document Properties shows, for example `textControl1.DocumentSettings.DocumentTitle = "Invoice INV-2025-001";`. The properties of the same name in [SaveSettings](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol/savesettings/llms-full.txt) override them when you save.

### Build Large Documents Without Undo

Each change in the editor goes into the undo history, and hundreds of paragraphs inserted by code make that history expensive in time and memory. Set [IsUndoEnabled](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/isundoenabled-property/llms-full.txt) to `false` while the code runs, as [Switch the Buffer Off](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-editor/editing-text/undo-redo/#switch-the-buffer-off) in Undo and Redo describes, and set it back to `true` in a `finally` block, so that an exception doesn't leave the editor without undo. A `ServerTextControl` has no undo history.

### Check the Fonts of a Document

Text is formatted with the fonts available for the printer that [FormattingPrinter](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/formattingprinter-property/llms-full.txt) names, and [GetSupportedFonts](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/getsupportedfonts-method/llms-full.txt) returns their names. A font that a document uses and that isn't supported is replaced; the [AdaptFont](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/reference/txtextcontrol-wpf/textcontrol/adaptfont-event/llms-full.txt) event reports each replacement and lets you choose the font, as [Choose the Replacement Fonts](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/pdf/fonts/#choose-the-replacement-fonts) in Font Embedding and Substitution shows. [Fonts and Document Layout](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/troubleshooting/fonts/llms-full.txt) helps when text looks different than expected.

### Next Steps

- [Loading Documents](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/loading/llms-full.txt): load existing documents with all their options.
- [Text, Paragraphs, and Stylesheets](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/text-paragraphs/llms-full.txt): format the text of the new document.
- [Saving and Converting Documents](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/saving-converting/llms-full.txt): save the finished document in the format you need.
- [Sections, Pages, Headers, and Footers](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/sections-headers/llms-full.txt): give parts of a document their own page format.

---

## Nearby

- **Previous:** [Document Object Model](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/object-model/llms-full.txt)
- **Next:** [Loading Documents](https://docs.textcontrol.com/tx-text-control-dotnet-wpf/document-processing/loading/llms-full.txt)
