DS Server

ASP.NET Core

Topic

Four NuGet packages connect a .NET application to DS Server. Two render the browser components in an ASP.NET Core MVC view, the Document Editor and the Document Viewer, and two call the Web API from C#: DocumentProcessing for documents and Admin for the administration of the server. Each package is listed below with its installation, its usage and the settings it accepts.

For a first application built step by step, follow the ASP.NET Core tutorials of Getting Started: Document Editor, Document Viewer and Document Processing.

Packages and Requirements

PackageVersionTarget frameworksDependencies
TXTextControl.DocumentServices.DocumentEditor5.0.0.NET 8, .NET 10Microsoft.AspNetCore.Html.Abstractions, Microsoft.AspNetCore.Mvc.ViewFeatures, Microsoft.AspNetCore.WebUtilities, Newtonsoft.Json
TXTextControl.DocumentServices.DocumentViewer5.0.0.NET 8, .NET 10The Microsoft.AspNetCore.App framework, Newtonsoft.Json
TXTextControl.DocumentServices.DocumentProcessing5.0.0.NET 8, .NET 10The Microsoft.AspNetCore.App framework, Newtonsoft.Json
TXTextControl.DocumentServices.Admin5.0.0.NET 8, .NET 10None

The packages are published on nuget.org, and each description says that version 5.0.0 is meant for DS Server 5.0.0. Besides the package, you need:

  • A running DS Server that you can reach from the browser and from your server, or a trial token for the trial server https://trial.dsserver.io, described in Trial Token.
  • A security profile with a client ID and a client secret, created in the admin portal as Creating Security Profiles shows. The Admin package needs the admin password instead.

Install a package with the .NET CLI in the folder of your project, or search for its name in the NuGet Package Manager of Visual Studio:

dotnet add package TXTextControl.DocumentServices.DocumentEditor

Authorization

The Document Editor and Document Viewer packages take the credentials of the security profile in OAuthSettings:

PropertyTypeDescription
ClientIdstringThe client ID of the security profile
ClientSecretstringThe client secret of the security profile
RedirectUristringThe OAuth redirect URI in your application that DS Server sends the authorization code to

The packages provide the callback endpoint themselves. Register its address in the security profile under the authorized redirect URIs, as the security profile table lists them:

PackageRedirect URI to register
DocumentEditorhttps://your.app/textcontrol/documenteditor/auth/callback
DocumentViewerhttps://your.app/textcontrol/documentviewer/auth/callback
DocumentProcessinghttps://your.app/textcontrol/documentprocessing/auth/callback

Replace https://your.app with the address of your application. With a trial token, leave out RedirectUri and set the service URL to https://trial.dsserver.io: the trial profile allows the client credentials grant type, which needs no redirect. Don't put the client secret into client-side code; in a Razor view, it stays on the server. Overview compares the ways of getting a token.

Document Editor

TXTextControl.DocumentServices.DocumentEditor renders the Document Editor, a word processor in the browser, from a Razor view. The editor's script and its document processing come from DS Server.

Usage

Add the editor to a view, such as Views/Home/Index.cshtml:

@using TXTextControl.DocumentServices.DocumentEditor

@Html.TXTextControl().DocumentEditor(settings => {
    settings.Width = "1000px";
    settings.Height = "600px";
    settings.ServiceUrl = "https://ds.example.com";
    settings.OAuthSettings.ClientId = "<client ID>";
    settings.OAuthSettings.ClientSecret = "<client secret>";
    settings.OAuthSettings.RedirectUri = "https://your.app/textcontrol/documenteditor/auth/callback";
}).Render()

The code works as follows:

  • Html.TXTextControl() is the extension method of the package's HtmlHelperExtension class, and DocumentEditor creates the editor with the settings of the lambda expression.
  • ServiceUrl is the address of your DS Server, the same one the browser uses.
  • Render writes the HTML of the editor into the view. RenderAsync does the same asynchronously.

DocumentEditorSettings Properties

PropertyDescription
WidthThe width of the editor as a CSS length, such as "100%" or "20em"
HeightThe height of the editor as a CSS length
PositionThe CSS position of the editor, a CSSPosition value
ServiceUrlThe URL of DS Server
OAuthSettingsOptional. The OAuth credentials, see Authorization
DocumentDataThe document to load, as a byte array. Text formats such as HTML or RTF must be UTF-8
DocumentFileFormatThe format of DocumentData, a StreamType value
JsonDataThe JSON data source that the Reporting tab offers as merge fields
EditModeWhether the text can be edited or only read, an EditMode value
CultureThe culture of the editor, a CultureInfo; it affects formats such as dates and times
UICultureThe culture of the user interface, a CultureInfo; it selects the language of the strings
FormattingPrinterThe name of a printer whose text dimensions and capabilities are used to format the document
ReconnectTimeoutThe time in seconds after which the editor stops trying to reconnect after the connection is lost
UserNamesThe names of the users who may edit the editable regions assigned to them
CustomQueryParamsCustom query parameters
WebSocketProtocolsAdditional WebSocket sub-protocols passed to every WebSocket the editor opens, for example for your own authentication

Enumerations

EditMode sets what the user can do with the text:

ValueDescription
EditThe text can be edited and formatted without restrictions
ReadAndSelectThe text is displayed and can be selected
ReadOnlyThe text is displayed only and can't be selected
UsePasswordA dialog box asks for a password that protects the edit mode; combine it with ReadAndSelect using the bitwise OR operator

StreamType names the format of DocumentData:

ValueFormat
HTMLFormatHTML
RichTextFormatRTF
PlainTextUnicode text; a paragraph ends with the control characters 13 and 10
InternalUnicodeFormatThe TX Text Control format
MSWordMicrosoft Word, DOC
XMLFormatXML
AdobePDFPDF; only the text is imported
WordprocessingMLMicrosoft Word, DOCX
SpreadsheetMLMicrosoft Excel, XLSX

CSSPosition has the values of the CSS position property: Static, Relative, Absolute, Fixed and Sticky. When Position isn't set, the package renders the editor's container with position:relative.

Once the editor is on the page, the browser controls it through the TXTextControl object of the Document Editor JavaScript API.

Document Viewer

TXTextControl.DocumentServices.DocumentViewer renders the Document Viewer, which displays documents, lets users annotate them and collects signatures.

Usage

Add the viewer to a view:

@using TXTextControl.DocumentServices.DocumentViewer

@await Html.TXTextControl().DocumentViewer(settings => {
    settings.DocumentData = "SGVsbG8gdGhlcmU=";
    settings.Dock = DocumentViewerSettings.DockStyle.Fill;
    settings.IsSelectionActivated = true;
    settings.ShowThumbnailPane = true;
    settings.BasePath = "https://ds.example.com";
    settings.OAuthSettings.ClientId = "<client ID>";
    settings.OAuthSettings.ClientSecret = "<client secret>";
    settings.OAuthSettings.RedirectUri = "https://your.app/textcontrol/documentviewer/auth/callback";
}).RenderAsync()

The viewer's URL of DS Server is BasePath, not ServiceUrl. DocumentData holds the document as a Base64-encoded string; the example shows the text "Hello there".

DocumentViewerSettings Properties

PropertyDescription
BasePathThe URL of DS Server
OAuthSettingsThe OAuth credentials, see Authorization
DocumentDataThe document to display, as a Base64-encoded string
DocumentPathThe document name the viewer displays
DocumentLoadSettingsHow the document is loaded, a DocumentLoadSettings object: LoadEmbeddedComments, whether comments in the document are loaded as annotations (true by default), and PDFJS, the WorkerSourcePath and LibrarySourcePath of PDF.js
DockHow the viewer is docked, a DockStyle value
ToolbarDockedWhether the toolbar is docked
IsSelectionActivatedWhether text can be selected
ShowThumbnailPaneWhether the pane of page thumbnails is visible when the viewer opens
ViewThe device-specific view, a ViewMode value: Mobile or Desktop
RenderModeHow the pages are rendered, a ComponentRenderMode value: Auto, Font, GlyphOutlines or Bitmap
FormattingPrinterThe name of a printer whose text dimensions and capabilities are used to format the document
UserNamesThe names of the users who have access to editable regions
ResourceManagerThe resource manager for the strings of the viewer
SignatureSettingsThe settings of a signature process, a SignatureSettings object
CustomQueryParamsCustom query parameters, a Dictionary<string, string>

DockStyle, nested in DocumentViewerSettings, has two values: Window fills the browser window, and Fill, the default, docks the viewer to all edges of its container.

SignatureSettings Properties

PropertyDescription
ShowSignatureBarWhether the signature bar is shown
OwnerNameThe name of the document owner
SignerNameThe name of the signer
SignerInitialsThe initials of the signer
SignatureBoxesThe boxes to sign, an array of SignatureBox objects
SignatureBoxNameObsolete: the name of the signature box; use SignatureBoxes
DefaultSignatureFontThe default font of text-based signatures, a SignatureFontSettings object with the font Family
UniqueIdA unique ID of the document envelope
RedirectUrlAfterSignatureThe URL the viewer redirects to after a successful signature
CustomSigningWhether your own code handles the signing process

A SignatureBox takes the name of the signature field in its constructor, such as new SignatureBox("txsign"), and has SigningRequired and a Style, SignatureBox.SignatureBoxStyle.Signature or SignatureBox.SignatureBoxStyle.Initials.

Once the viewer is on the page, the browser controls it through the TXDocumentViewer object of the Document Viewer JavaScript API.

DocumentProcessing

TXTextControl.DocumentServices.DocumentProcessing sends documents to the DocumentProcessing Web API and returns the results as byte arrays. It has no user interface and runs in any .NET 8 or .NET 10 application.

Usage

A controller action that converts a document to PDF:

using Microsoft.AspNetCore.Mvc;
using TXTextControl.DocumentServices.DocumentProcessing;
using TXTextControl.DocumentServices.DocumentProcessing.OAuth;

public class ConvertController : Controller
{
    public async Task<IActionResult> Index()
    {
        // Credentials of the security profile
        var oauthSettings = new OAuthSettings(
            "<client ID>",
            "<client secret>",
            "https://your.app/textcontrol/documentprocessing/auth/callback");

        var documentProcessing = new DocumentProcessing("https://ds.example.com", oauthSettings);

        byte[] document = await System.IO.File.ReadAllBytesAsync("App_Data/sample.docx");
        byte[] pdf = await documentProcessing.Convert(document, ReturnFormat.PDF);

        return File(pdf, "application/pdf", "sample.pdf");
    }
}

The code works as follows:

  • OAuthSettings takes the client ID, the client secret and the redirect URI. With a trial token, pass only the client ID and the secret.
  • The DocumentProcessing constructor takes the URL of DS Server and the OAuth settings. When OAuth is disabled on the server, the URL alone is enough. Use the constructor: in version 5.0.0 of the package, DocumentProcessing.CreateInstanceAsync requests an access token but doesn't send it with the requests that follow, so they fail with 401 when OAuth is enabled.
  • Convert sends the document to DS Server and returns it in the format of the ReturnFormat value. An overload takes a third argument, flattenFormFields.

DocumentProcessing Methods

MethodWeb API endpointReturns
ConvertPOST /documentprocessing/document/convertThe document in another format
MergePOST /documentprocessing/document/mergeThe documents merged from a template and JSON data, as an array of byte arrays. The overloads without the append argument send append=false, one document per record, while the Web API's default is true
FindAndReplacePOST /documentprocessing/document/findandreplaceThe document with text replaced
AppendPOST /documentprocessing/document/appendOne document combined from several
ThumbnailsPOST /documentprocessing/document/thumbnailsAn image of each page, as PNG, JPG, BMP, GIF or SVG; the longest overload also sends maxImageResolution, 96 by default
InfoPOST /documentprocessing/document/infoA DocumentInfo with the properties, merge fields and merge blocks of the document
InstalledPrintersGET /documentprocessing/document/installedprintersThe printers installed on the DS Server machine, as PrinterInfo objects. In version 5.0.0, a failed request throws a plain Exception without a status code
PDF.CreatePOST /documentprocessing/pdf/createA PDF or PDF/A document
PDF.GetEmbeddedFilesPOST /documentprocessing/pdf/embeddedfilesThe files embedded in a PDF document
PDF.GetMetaDataPOST /documentprocessing/pdf/metadataThe metadata of a PDF document
PDF.AcroForms.GetFieldsPOST /documentprocessing/pdf/acroforms/fieldsThe AcroForm fields of a PDF document
Barcodes.CreatePOST /documentprocessing/barcodes/createA barcode image of the text in a BarcodeSettings object, a QR code by default
Barcodes.GetDefaultTextGET /documentprocessing/barcodes/defaulttextThe default text of a barcode type
Barcodes.GetMaximumTextLength, Barcodes.GetMinimumTextLengthGET /documentprocessing/barcodes/maximumtextlength, GET /documentprocessing/barcodes/minimumtextlengthThe maximum or minimum text length of a barcode type
Barcodes.IsTextValidGET /documentprocessing/barcodes/istextvalidWhether a text is valid for a barcode type

ReturnFormat has the values PDF, PDFA, DOC, DOCX, RTF, TX, TXT and HTML. RefreshAccessToken requests a new access token with the refresh token, which only the authorization code flow issues; with the client credentials grant type, it throws an exception. OAuthInfo returns the OAuth information in use, such as the GrantType and ExpiresIn, or null when OAuth isn't used. .NET API lists the classes of the package.

Admin

TXTextControl.DocumentServices.Admin calls the administration endpoints of DS Server, so that you can automate what the admin otherwise does in the admin portal. Its Admin class takes the URL of DS Server and the password of the admin user:

MethodDoes
GetSecurityProfileIds, GetSecurityProfileReturn the IDs of all security profiles, or one profile by ID
AddSecurityProfile, DeleteSecurityProfileAdd a SecurityProfile and return its ID, or delete one by ID
UpdateAllowClientCredentialsGrantTypeAllow or forbid the client credentials grant type for a profile
UpdateExpiryDateSet the expiry date of a profile
UpdateAuthorizedRedirectUrisSet the authorized redirect URIs of a profile
GetOAuthEnabled, SetOAuthEnabledRead or switch whether OAuth is enabled
GetAuthenticationServerIds, GetAuthenticationServer, AddAuthenticationServer, DeleteAuthenticationServer, UpdateServerUrlManage the authentication servers
ChangeUserPasswordChange the password of a user; the new password has at least eight characters

A SecurityProfile takes its name in the constructor, such as new SecurityProfile("My App"), and has an ID, a Name, a CreationDate, an optional ExpiryDate, AllowClientCredentialsGrantType and optional ClientCredentials, which hold the client ID, the Secret and the AuthorizedRedirectUris. A failed request throws a ServiceRequestException with the HTTP StatusCode. The Administration endpoints of the Web API describe the requests behind the methods.