# Saving Documents

> Save documents from the Document Viewer: saveDocument with form values and annotations, DocumentSaveResult, posting it to a controller and downloadDocument.

- **Product:** TX Text Control .NET Server
- **Section:** Documentation
- **Kind:** Topic
- **Path:** TX Text Control .NET Server > Document Viewer > Saving Documents
- **2337 words**
- **Web URL:** https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/saving/
- **LLMs URL:** https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/saving/llms.txt
- **LLMs-Full URL:** https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/saving/llms-full.txt

---

To store what users did in the Document Viewer, for example a filled out form, your code gets the document back out of the viewer. It saves the document in a format with the values of form fields and the annotations, sends the result to your server or lets users download it as PDF.

The examples extend the application of [Loading Documents](https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/loading/llms-full.txt), whose *Controllers/DocumentController.cs* contains the `DocumentData` class.

### Ways to Get a Document Out of the Viewer

| You need | Use |
|---|---|
| The document as data for your code, with the values of the form fields or the annotations | [saveDocument](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/javascript-document-viewer/documentviewercontroller/savedocument-method/llms-full.txt) |
| A PDF file that the user downloads | [downloadDocument](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/javascript-document-viewer/documentviewercontroller/downloaddocument-method/llms-full.txt), or the download button of the toolbar |
| Only the annotations, stored separately from the document | `annotations.export`, described in [Import and Export](https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/annotations/import-export/llms-full.txt) |
| Only the values of the form fields | `forms.getValues`, described in [Form Fields](https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/form-fields/llms-full.txt) |

Saving documents with `saveDocument` is available since version 32.0.2 of the Document Viewer package.

### Save a Document and Send It to the Server

The following code saves the document as PDF with the values of the form fields and the annotations, and posts it to a controller. Add it below the viewer's `div` in *Views/Home/Index.cshtml*:

```html
<input type="button" onclick="saveToServer()" value="Save as PDF" />

<script>
    async function saveToServer() {
        const result = await TXDocumentViewer.saveDocument(
            TXDocumentViewer.StreamType.AdobePDF,
            { mergeFormFields: true, embedAnnotations: true });

        const base64 = await result.base64();

        const response = await fetch("/Document/Save", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ name: "result.pdf", data: base64 })
        });

        console.log(response.ok ? "Document saved." : "Saving failed: " + response.status);
    }
</script>
```

Add the action that stores the document to *Controllers/DocumentController.cs*:

```csharp
// Store a document that saveDocument created
[HttpPost]
public IActionResult Save([FromBody] DocumentData documentData)
{
    var file = Path.Combine("App_Data", Path.GetFileName(documentData.Name));
    System.IO.File.WriteAllBytes(file, Convert.FromBase64String(documentData.Data));

    return Ok();
}
```

The code works as follows:

- `saveDocument` takes a value of [TXDocumentViewer.StreamType](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/javascript-document-viewer/streamtype/enumeration/llms-full.txt) and a [DocumentSaveSettings](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/javascript-document-viewer/documentsavesettings/llms-full.txt) object. It returns a promise that resolves to a [DocumentSaveResult](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/javascript-document-viewer/documentsaveresult/llms-full.txt).
- [base64](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/javascript-document-viewer/documentsaveresult/base64-method/llms-full.txt) returns a promise with the document as a base64-encoded string. [arrayBuffer](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/javascript-document-viewer/documentsaveresult/arraybuffer-method/llms-full.txt) returns the data as an `ArrayBuffer` instead.
- The `Save` action decodes the string and writes the file into the *App\_Data* folder. `Path.GetFileName` keeps the name from pointing outside the folder.

Run the application, fill out a form field or add an annotation and click **Save as PDF**: the *App\_Data* folder contains *result.pdf*.

#### Formats and Settings

`TXDocumentViewer.StreamType` contains four formats:

| Value | Format |
|---|---|
| `AdobePDF` | PDF |
| `WordprocessingML` | DOCX |
| `InternalUnicodeFormat` | The TX Text Control format |
| `MSWord` | DOC; the Core engine doesn't support DOC documents |

`DocumentSaveSettings` has two settings:

- [mergeFormFields](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/javascript-document-viewer/documentsavesettings/mergeformfields-property/llms-full.txt) sets whether the values of the form fields are merged into the document.
- [embedAnnotations](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/javascript-document-viewer/documentsavesettings/embedannotations-property/llms-full.txt) sets whether the annotations are stored in the document.

When a PDF document is displayed with PDF.js and saved as `AdobePDF`, the values of its form fields are exported into the PDF document.

### Convert the Document on the Server

To process the document further on the server, save it in the TX Text Control format, which keeps all its elements, and convert it there with `ServerTextControl`. Change `saveToServer` so that it calls `saveDocument` with `TXDocumentViewer.StreamType.InternalUnicodeFormat`, sends the name *result.tx* and posts to `/Document/SaveAsPdf`. Add `using TXTextControl;` at the top of *Controllers/DocumentController.cs* and this action:

```csharp
[HttpPost]
public IActionResult SaveAsPdf([FromBody] DocumentData documentData)
{
    var file = Path.Combine("App_Data",
        Path.ChangeExtension(Path.GetFileName(documentData.Name), ".pdf"));

    using (ServerTextControl tx = new ServerTextControl())
    {
        tx.Create();

        // Load the document that saveDocument created in the TX Text Control format
        tx.Load(Convert.FromBase64String(documentData.Data), BinaryStreamType.InternalUnicodeFormat);
        tx.Save(file, StreamType.AdobePDF);
    }

    return Ok();
}
```

- [ServerTextControl.Load](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/txtextcontrol/servertextcontrol/load-method/llms-full.txt) loads the decoded data with `InternalUnicodeFormat` from [BinaryStreamType](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/txtextcontrol/binarystreamtype/enumeration/llms-full.txt).
- [Save](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/txtextcontrol/servertextcontrol/save-method/llms-full.txt) writes the PDF file with `AdobePDF` from [StreamType](https://docs.textcontrol.com/tx-text-control-dotnet-server/reference/txtextcontrol/streamtype/enumeration/llms-full.txt).

Between loading and saving, your code can process the document, for example read its form fields. The blog article [Document Viewer: Save the Values of Form Fields in Documents](https://www.textcontrol.com/blog/2023/12/19/document-viewer-save-the-values-of-form-fields-in-documents/) shows this process.

### Download the Document as PDF

Users download the document with a button of the toolbar. A button of your own calls `downloadDocument`, which downloads the current document as a PDF file to the user's computer. It takes no parameters and returns nothing:

```html
<input type="button" onclick="TXDocumentViewer.downloadDocument()" value="Download PDF" />
```

[Printing](https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/printing/llms-full.txt) describes the download together with printing.

### Next Steps

- [Form Fields](https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/form-fields/llms-full.txt): validate and read the values users enter.
- [Import and Export](https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/annotations/import-export/llms-full.txt): store annotations separately from the document.
- [Saving and Converting Documents](https://docs.textcontrol.com/tx-text-control-dotnet-server/document-processing/saving-converting/llms-full.txt): process documents on the server with `ServerTextControl`.

---

## Nearby

- **Previous:** [Loading Documents](https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/loading/llms-full.txt)
- **Next:** [Navigation](https://docs.textcontrol.com/tx-text-control-dotnet-server/document-viewer/navigation/llms-full.txt)
