> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/web/get-started/samples/webviewer-annotations-aspnet.md).

# Save and Load Annotations with ASP.NET

Save and load annotations to disk using XFDF and HTTP messaging

In addition to showing how to add the WebViewer component to an ASP.NET project, this sample expands on annotation functionality by enabling saving and loading the annotation objects into the local file system.

The saving and loading are done through GET and POST HTTP messages that are handled by an `AnnotationController` in the project. The annotations are stored as [XFDF](/web/annotation/xfdf.md) strings embedded in the messages and saved as XFDF files on disk.

WebViewer provides a slick out-of-the-box responsive UI that enables you to view, annotate and manipulate PDFs and other document types inside any web project.

Click the button below to view the full project in GitHub.

{% tabs %}
{% tab title="index.js" %}
{% code title="index.js" lineNumbers="true" %}

```js
var viewerElement = document.getElementById('viewer');
var DOCUMENT_ID = 'webviewer-demo-1';

WebViewer({
  path: '/Scripts/webviewer/lib',
  initialDoc: 'https://pdftron.s3.amazonaws.com/downloads/pl/demo.pdf',
  documentXFDFRetriever: () => loadXfdfString(DOCUMENT_ID)
}, viewerElement).then(instance => {
  const {annotationManager} = instance.Core;
  
  // Add a save button on header
  const topHeader = instance.UI.getModularHeader('default-top-header');
  const items = topHeader.getItems();
  
  const saveButton = {
    type: 'customButton',
    img: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg>',
    title: 'Save Annotations',
    onClick: function() {
      // Save annotations when button is clicked
      // widgets and links will remain in the document without changing so it isn't necessary to export them
      annotationManager.exportAnnotations({ links: false, widgets: false }).then(function (xfdfString) {
        saveXfdfString(DOCUMENT_ID, xfdfString)
        .then(function() {
          alert('Annotations saved successfully.');
        })
        .catch(function () {
          alert('Annotations not saved successfully.');
        });
      });
    }
  };

  items.push(saveButton);
  topHeader.setItems(items);
});

// Make a POST request with XFDF string
var saveXfdfString = function(id, xfdfString) {
  return new Promise(function(resolve) {
    fetch(`/api/annotation?id=${id}`, {
      method: 'POST',
      body: xfdfString
    }).then(function(res) {
      if (res.status === 200 || res.status === 204) {
        resolve();
      }
    });
  });
};

// Make a GET request to get XFDF string
var loadXfdfString = function(id) {
  return new Promise(function(resolve) {
    fetch(`/api/annotation?id=${id}`, {
      method: 'GET'
    }).then(function(res) {
      if (res.status === 200 || res.status === 204) {
        res.text().then(function(xfdfString) {
          resolve(xfdfString);
        });
      }
    });
  });
};

```

{% endcode %}
{% endtab %}

{% tab title="AnnotationController.cs" %}
{% code title="AnnotationController.cs" lineNumbers="true" %}

```csharp
﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

/**
 * AnnotationController.cs
 * This is a sample of basic server-side annotation handling using ASP.NET.
 * When WebViewer makes a POST request with annotations to save, this script will save the annotations to a file.
 * When WebViewer makes a GET request to load the annotations, this script will fetch the annotations from the file and return it.
 * Note that this is only a sample and does not take account of security and concurrency.
 **/

namespace WebApplication1.Controllers
{
    public class AnnotationController : ApiController
    {
        // Handle GET request sent to '/api/annotation'
        // GET api/<controller>
        public HttpResponseMessage Get()
        {
            string filePath = GetFilePath(this.Request);
            if (File.Exists(filePath))
            {
                // Read from the XFDF file and send the string as a response
                string xfdfData = File.ReadAllText(filePath);
                return new HttpResponseMessage() { Content = new StringContent(xfdfData) };
            }
            else
            {
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }

        // Handle POST request sent to '/api/annotation'
        // POST api/<controller>
        public async Task Post()
        {
            string filePath = GetFilePath(this.Request);
            string xfdfData = await Request.Content.ReadAsStringAsync();
            File.WriteAllText(filePath, xfdfData);
        }

        private string GetFilePath(HttpRequestMessage request)
        {
            string id = GetId(request);
            string fileName = (id != null) ? id : "default";
            return System.Web.HttpContext.Current.Server.MapPath(string.Format("~\\{0}.xfdf", fileName));
        }

        private string GetId(HttpRequestMessage request)
        {
            var pairs = Request.GetQueryNameValuePairs();
            string documentId = null;
            foreach (KeyValuePair<string, string> kvp in pairs)
            {
                if (kvp.Key == "id")
                {
                    documentId = kvp.Value;
                }
            }

            return documentId;
        }
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

[View the full sample on GitHub](https://github.com/ApryseSDK/webviewer-samples/tree/main/webviewer-annotations-aspnet)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/web/get-started/samples/webviewer-annotations-aspnet.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
