Converter Plugin

Convert documents to 45 target formats

The Converter plugin turns Doconut into a document-conversion service. It contributes the engine behind the public DocumentConverter facade and — opt-in — a drop-in widget served by DocImage.axd, so you can convert documents from C#, from the widget, or from a frontend you write yourself.

SurfaceUse it when
DocumentConverter (C#)You convert on the server, with no browser involved
Drop-in widget (doconutConverter.js)You want a ready-made upload, convert and download screen in your page
HTTP endpoints on DocImage.axd (?convert=open|run|download)You build your own conversion UI against a documented server contract

Install the package

powershell
Install-Package Doconut.NETFramework.Converter

To pin the plugin to the release this documentation describes:

powershell
Install-Package Doconut.NETFramework.Converter -Version 26.10.0

Keep the Converter package at the same version as Doconut.NETFramework.

The plugin's license file, Doconut.Viewer.Converter.lic, goes in the same folder as Doconut.Viewer.lic; it is read together with the viewer license.

Register the plugin

Every plugin registers the same way: AddPlugin<TPlugin>() in DoconutHost.Initialize, called from Application_Start.

csharp
Doconut.DoconutHost.Initialize(options =>
{
    options.LicensePath = HostingEnvironment.MapPath("~/wwwroot/Doconut.Viewer.lic");
    options.AddPlugin<Doconut.Plugins.Converter.ConverterPlugin>();
});

That is all the C# facade needs. The widget and its HTTP endpoints are a separate opt-in, AddConverterWidget() (see Drop-in widget).

The plugin needs a license that grants the Converter capability. Without one, DoconutHost.Initialize throws from Application_Start:

text
The Converter plugin is registered via AddPlugin but no active license grants Converter. Remove the AddPlugin<...>() call or install a license (or trial/demo) that includes Converter.

In System.Web that means every request answers an empty 500, and the reason is only in the Windows event log (source ASP.NET). It throws for no license, a legacy TRIAL file, a license without Converter, and a paid license used outside its version window. Temporary Demo/NFR licenses are accepted. See License Setup.

Licensing & watermark

License stateStartupConversion output
Paid viewer license granting Converter, within its version windowStartsClean — watermarked: false
Active Temporary (Demo/NFR) licenseStartsConverts, with the evaluation watermark — watermarked: true
Expired Temporary (Demo/NFR) licenseStartsConverts, with the evaluation watermark — watermarked: true
No license, a legacy TRIAL file, a license without Converter, or a paid license outside its version windowApplication_Start throws; every request answers an empty 500—

The DocumentConverter facade and the widget's ?convert=run handler apply the same rule. An integration can be built and tested end to end on an evaluation license before purchase — only the output bytes change.

A DICOM source (.dcm, .ima) also needs the Dicom capability. Without it, ConvertAsync throws a LicenseException (Converting '.dcm' requires the Dicom capability license.) and the widget's open answers 403.

Use from C#

Every conversion returns a seekable MemoryStream positioned at 0. DocumentConverter is stateless: resolve it from DoconutHost.Services wherever you need it and reuse it freely.

csharp
// Resolve DocumentConverter from DoconutHost.Services; its constructor is internal, so never `new` it.
Stream pdf = await converter.ConvertAsync("contract.docx", ConversionTarget.Pdf, ct: ct);
csharp
// sourceExtension includes the leading dot. password is null unless the document is protected.
Stream png = await converter.ConvertAsync(stream, ".xlsx", ConversionTarget.Png, password: null, ct: ct);
csharp
Stream html = await converter.WordToHtmlAsync("report.docx", ct);
csharp
// html: a Stream holding the HTML to turn back into a Word document, such as the result of WordToHtmlAsync.
Stream docx = await converter.HtmlToWordAsync(html, ConversionTarget.Docx, ct);

Two details that are easy to get wrong: sourceExtension on the stream overload must include the leading dot (".xlsx", not "xlsx"), or it does not resolve. And despite its name, WordToHtmlAsync returns Task<Stream>, not Task<string> — the HTML document (images embedded as Base64) arrives as a stream, like every other result.

The caller owns the MemoryStream a conversion returns and should dispose it after copying or returning it (MVC's File(stream, …) disposes it for you). Do not construct or dispose DocumentConverter yourself — its constructor is internal.

In an MVC 5 controller

Make the action asynchronous and await the conversion:

csharp
[HttpPost]
public async Task<ActionResult> ToPdf(HttpPostedFileBase file)
{
    var converter = Doconut.DoconutHost.Services.GetRequiredService<DocumentConverter>();
    Stream pdf = await converter.ConvertAsync(
        file.InputStream, Path.GetExtension(file.FileName), ConversionTarget.Pdf,
        password: null, ct: Response.ClientDisconnectedToken);
    return File(pdf, "application/pdf", Path.GetFileNameWithoutExtension(file.FileName) + ".pdf");
}

In Web Forms: never block on a conversion

A Web Forms page runs on a single-threaded request context. ConvertAsync resumes on that context when it completes, so a page that waits for it synchronously — .Result, .Wait(), .GetAwaiter().GetResult() — holds the very thread the conversion needs to finish. The request never returns. The browser keeps spinning, IIS logs nothing, and the rest of the site keeps working, so it looks like a slow conversion rather than a deadlock.

Mark the page Async="true" and run the conversion as a page async task:

aspx
<%@ Page Language="C#" Async="true" CodeBehind="Convert.aspx.cs" Inherits="MyApp.Convert" %>
csharp
// Web Forms: the @Page directive needs Async="true", and the conversion runs as a page async task.
// Blocking on it instead (.Result, .Wait(), .GetAwaiter().GetResult()) deadlocks the request:
// it never returns, and nothing is logged.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack) return;

    RegisterAsyncTask(new PageAsyncTask(async ct =>
    {
        var converter = Doconut.DoconutHost.Services.GetRequiredService<DocumentConverter>();

        using (var pdf = await converter.ConvertAsync(
                   Server.MapPath("~/App_Data/contract.docx"), ConversionTarget.Pdf, ct: ct))
        using (var ms = new MemoryStream())
        {
            if (pdf.CanSeek) pdf.Position = 0;
            await pdf.CopyToAsync(ms);

            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment; filename=contract.pdf");
            Response.BinaryWrite(ms.ToArray());
            // Context, not HttpContext.Current: after an await the latter can be null.
            Context.ApplicationInstance.CompleteRequest();
        }
    }));
}

Without Async="true" in the @Page directive, RegisterAsyncTask is silently ignored. After an await, use the page's Context; HttpContext.Current can be null there.

Target formats

ConversionTarget (namespace Doconut.Configs.Conversion) has 45 members:

text
Pdf, Docx, Doc, Html, Xlsx, Pptx, Png, Jpeg, Csv, Tiff, Bmp, Gif, Svg, Xml,
Txt, Xls, Jp2, Rtf, Odt, Ods, Odp, Epub, Xps, Webp, Msg, Eml, Emlx, Mhtml,
Xlsm, Xlsb, Ppt, Docm, Dot, Dotx, Dotm, Vsdx, Vssx, Vstx, Vsdm, Vssm, Vstm,
Vdx, Vsx, Vtx, Ico

Not every source converts to every target: each source's format family (Word, Excel, PowerPoint, PDF, CAD, Image, Email, Diagram, Project, PSD, web document, DICOM) has its own set of allowed targets. Converting a DICOM source (.dcm, .ima) also needs a license that grants the Dicom capability; its targets are Pdf, Png, Jpeg, Bmp, Tiff and Gif. Don't hardcode this enum as your UI's target list: ?convert=open returns the allowedTargets for the uploaded file, and that is what should drive a picker.

Drop-in widget

Enable the endpoints

The widget's ?convert=open|run|download endpoints are served by DocImage.axd and are off by default. Enable them next to the plugin registration:

csharp
Doconut.DoconutHost.Initialize(options =>
{
    options.LicensePath = HostingEnvironment.MapPath("~/wwwroot/Doconut.Viewer.lic");
    options.AddPlugin<Doconut.Plugins.Converter.ConverterPlugin>();
    options.AddConverterWidget(widget =>
    {
        widget.MaxUploadMb = 25;
    });
});
// System.Web reads the whole upload before Doconut sees it: keep maxRequestLength (KB) and
// maxAllowedContentLength (bytes) in Web.config above the widget's MaxUploadMb.

AddConverterWidget() with no argument enables the widget with the defaults (MaxUploadMb = 25). It does not grant conversion rights by itself: it needs AddPlugin<ConverterPlugin>(), or DoconutHost.Initialize throws:

text
AddConverterWidget() was called but the Converter plugin is not registered. Add options.AddPlugin<Doconut.Plugins.Converter.ConverterPlugin>() (the widget needs it), or remove the AddConverterWidget() call.

Two things to check when the widget misbehaves:

  • basePath: '/DocImage.axd'. The widget's default, /doconut, is the ASP.NET Core endpoint. On this package, the endpoints are the DocImage.axd handler from Web.config.
  • The script and the endpoints are independent. The resource module serves doconutConverter.js whether or not the widget is enabled. Without AddConverterWidget(), the widget loads, paints its drop zone, and looks entirely correct — and its first action answers 404.

Upload limits

ASP.NET reads the whole request body before DocImage.axd runs. An upload above MaxUploadMb but below the host limits gets the widget's own JSON 413 (File is too large.). An upload above the host limits is rejected by IIS first, with an error page the widget cannot read. Keep both host limits in Web.config above the widget's cap:

xml
<system.web>
  <httpRuntime maxRequestLength="30720" />           <!-- KILOBYTES: 30 MB -->
</system.web>
<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="31457280" />  <!-- BYTES: 30 MB -->
    </requestFiltering>
  </security>
</system.webServer>

Embed it

html
<div id="doconut-convert"></div>
<script src="/doconut-res/js/doconutConverter.js"></script>
<script>
  Doconut.convert('#doconut-convert', { basePath: '/DocImage.axd', maxUploadMb: 25 });
</script>

Doconut.convert(selectorOrElement, options) takes a CSS selector or an element, throws if the mount is not found, and returns a handle. The widget uploads a file, shows a preview of page 1, lets the user pick one of the allowedTargets, converts, previews the result when it can, and offers the download.

Options

OptionTypeDefaultNotes
basePathstring/doconutThe endpoint URL. Set '/DocImage.axd' on this package
resPathstring/doconut-resAccepted for consistency with other Doconut widgets; the converter widget does not build any URL from it
maxUploadMbnumber25Client-side pre-check only; the server enforces its own cap
licenseUrlstring | nullnullTurns the watermark notice on the result screen into a link
labelsobject{}Overrides any subset of the widget's English strings

Callbacks

CallbackFires whenPayload
onReady()The widget has rendered its drop screen—
onSourceLoaded({ token, pages, sourceExt, allowedTargets })?convert=open succeedsSource token, page count, source extension (no leading dot), allowed targets
onConverted({ downloadToken, resultToken, resultPages, downloadName, watermarked, target })?convert=run succeedsThe run response plus the requested target
onDownload({ downloadName, downloadToken })The user clicks DownloadFires alongside the browser's own download
onError({ phase, message })An open or run request failsphase is 'open' or 'run'; message is the sanitized server error

A callback that throws is caught and logged; it never breaks the widget's flow.

Imperative handle

Doconut.convert() returns the widget instance:

javascript
const conv = Doconut.convert('#doconut-convert', { basePath: '/DocImage.axd' });
const file = document.querySelector('#picker').files[0]; // a File from your own <input type="file" id="picker">
conv.reset();         // back to the drop screen; does not re-fire onReady
conv.loadFile(file);  // starts the flow with a File; no-op unless the widget is at its drop screen
conv.destroy();       // removes listeners, empties the mount; the instance is unusable after this

Labels

Every string has an English default; labels overrides any subset and the rest stay English. Fragments that change at runtime use {placeholders}, such as uploading: 'Uploading {name}…' and pages: '{n} pages'.

KeyEnglish default
dropPromptDrag & drop a document here
dropHintPDF, Word, Excel, PowerPoint, images and more
chooseFileChoose file
uploadingUploading {name}…
page / pages1 page / {n} pages
noTargetsNo conversion targets are available for this file.
convertTo / convertConvert to / Convert
convertingConverting to {target}…
readyToDownloadReady to download
download / convertAnotherDownload / Convert another
watermarkNoticeOutput is watermarked — get a license to remove it.
retryRetry
genericErrorSomething went wrong. Please try again.
sizeLimitThat file is larger than the {mb} MB upload limit. Please choose a smaller file.
serverErrorThe server could not process this request. Please try again.
networkErrorCould not reach the server. Please check your connection and try again.

Further keys cover the drop zone's aria-label (dropAriaLabel), the preview alt texts (previewAlt, resultAlt), the linked form of the watermark notice used with licenseUrl (watermarkNoticePrefix, watermarkNoticeLink, watermarkNoticeSuffix), an unreadable response (badResponse) and the aria-live announcements (annReady, annUploading, annLoaded, annLoadedNoTargets, annConverting, annDone, annError).

A JSON error from the server is shown as the server wrote it; serverError is used only when a failed response carries no JSON error, such as the 404 of a disabled widget.

Theming

The widget adds the dcw class to its mount element and reads its colors, radius and font from CSS custom properties, so you can theme it without touching its internals:

css
#doconut-convert.dcw {
  --dcw-accent: #6b46c1;
  --dcw-radius: 12px;
  --dcw-font: "Inter", system-ui, sans-serif;
}

Defaults: --dcw-accent: #2b6cb0, --dcw-bg: #ffffff, --dcw-fg: #1a202c, --dcw-muted: #718096, --dcw-border: #cbd5e0, --dcw-radius: 8px, and a system UI font for --dcw-font.

Build your own frontend

The widget is a client for this HTTP contract on DocImage.axd. The routes answer 404 until AddConverterWidget() is called. Errors carry a JSON body, { "error": "..." }, except where the table says "status only". An unknown ?convert= value answers 400.

RoutePurposeSuccess response
POST /DocImage.axd?convert=open (multipart, one file)Upload and open a source document200 — { token, pages, sourceExt, allowedTargets }
POST /DocImage.axd?token=<token>&convert=run&target=<ext>Convert the uploaded source to target200 — { downloadToken, resultToken, resultPages, downloadName, watermarked }
GET /DocImage.axd?convert=download&token=<downloadToken>Stream the converted file200 — the file, Content-Disposition: attachment, Cache-Control: no-store

sourceExt in the open response has no leading dot ("docx") — the opposite of the sourceExtension parameter of ConvertAsync. allowedTargets lists lower-case target names ("pdf", "html", …); pass one of them as target, which is matched case-insensitively. open uses the first file in the multipart body.

resultToken is null, and resultPages is 0, when the result cannot be previewed. downloadName is the source file name with the target's extension.

The preview images use the standard viewer image route, /DocImage.axd?token={token}&page=1&thumb=1&width={px}, with the token from open or the resultToken from run. The widget asks for width=240.

Uploaded sources are kept for 30 minutes after they were last read; after that, run answers 404 and the file must be opened again. downloadToken gets its own 30-minute window when the conversion completes. resultToken is an ordinary viewer token for previewing the result; when the result can be previewed, it is the same value as downloadToken.

RouteStatusWhenBody
any404The widget isn't enabled (AddConverterWidget() was never called)status only
any405Wrong verb (open/run require POST, download requires GET)status only
open400Not a multipart uploadExpected a multipart file upload.
open400No file, or an empty oneNo file uploaded.
open400A type that cannot be convertedThis file type cannot be converted.
open403The file type needs a capability the license does not grant (a DICOM file without Dicom)Converting this file type requires the Dicom capability license.
open413The upload exceeds MaxUploadMb (but not the IIS limits)File is too large.
run400A malformed token (not a GUID)Invalid token.
run400A target that doesn't parse to a ConversionTargetUnknown target format.
run400A target not in allowedTargetsThat target format is not available for this file.
run404The upload expired or was never openedUpload expired — please re-open the file.
open, run500Processing failedA sanitized message
download400 / 404A malformed, unknown, or expired download tokenstatus only

A complete round trip with fetch:

javascript
// file: the File to convert, for example from an <input type="file">.
async function convertFile(file) {
  const base = '/DocImage.axd';

  // 1. open: upload the file
  const form = new FormData();
  form.append('file', file, file.name);
  const openResp = await fetch(base + '?convert=open', { method: 'POST', body: form });
  if (!openResp.ok) throw new Error((await openResp.json()).error);
  const opened = await openResp.json();

  // 2. run: convert to PDF when it is allowed, otherwise to the first allowed target
  const target = opened.allowedTargets.includes('pdf') ? 'pdf' : opened.allowedTargets[0];
  const runResp = await fetch(base + '?token=' + encodeURIComponent(opened.token) +
    '&convert=run&target=' + target, { method: 'POST' });
  if (!runResp.ok) throw new Error((await runResp.json()).error);
  const converted = await runResp.json();

  // 3. download: a plain GET the browser can follow
  window.location.href = base + '?convert=download&token=' + encodeURIComponent(converted.downloadToken);
}

The endpoints are same-origin: this version has no CORS support. Serve your UI and the widget script from the same origin as Doconut, or reverse-proxy the handler and the resource paths under your UI's origin.

In production

  1. Install the plugin next to the core package, at the same version: Install-Package Doconut.NETFramework.Converter.
  2. Add the license file. Put Doconut.Viewer.Converter.lic in the same folder as Doconut.Viewer.lic.
  3. Set the upload caps. MaxUploadMb in AddConverterWidget is the limit Doconut enforces; keep maxRequestLength and maxAllowedContentLength in Web.config above it (see Upload limits), and the widget's maxUploadMb equal to it.
  4. Never block on a conversion in Web Forms (see In Web Forms).
  5. Dispose conversion results. The stream ConvertAsync returns is pooled; disposing it returns its buffers to the pool.

Web farms

The widget keeps each upload and its result in memory on the server that served open. Behind a load balancer without sticky sessions, a later run, download or preview request can reach another server and not find the upload. Register the shared, encrypted widget store through the second argument of DoconutHost.Initialize:

csharp
byte[] farmKey = Convert.FromBase64String(System.Configuration.ConfigurationManager.AppSettings["Doconut:FarmKey"]);

Doconut.DoconutHost.Initialize(
    options =>
    {
        options.LicensePath = HostingEnvironment.MapPath("~/wwwroot/Doconut.Viewer.lic");
        options.AddPlugin<Doconut.Plugins.Converter.ConverterPlugin>();
        options.AddConverterWidget();
    },
    services => services.AddDoconutDistributedWidgets(store =>
    {
        store.RootPath = @"\\fileshare\doconut";   // a folder every server can read and write
        store.FarmKey = farmKey;                   // at least 32 bytes, identical on every server
        // store.Ttl = TimeSpan.FromMinutes(30);   // how long an upload is kept (the default)
    }));
  • A single server needs nothing: without this call the in-memory store is used.
  • Uploads and results are encrypted at rest on the share (AES-256, encrypt-then-MAC), and each file is bound to its token, so one token can never read another's file.
  • On the share, an upload or a result is kept for Ttl after it was written; reading it does not extend that window.
  • FarmKey must be at least 32 bytes and the same on every server. Load it from a secret store; never hard-code it. Registration throws an ArgumentException when RootPath is missing or FarmKey is shorter than 32 bytes.
  • Point RootPath at the same shared location the distributed viewer uses.

API reference

The facade and the widget options are in the Doconut namespace; ConversionTarget is in Doconut.Configs.Conversion. ConverterPlugin is in Doconut.Plugins.Converter.

DocumentConverter

csharp
public sealed class DocumentConverter
{
    public Task<Stream> ConvertAsync(
        string filePath, ConversionTarget target,
        string? password = null, CancellationToken ct = default);

    public Task<Stream> ConvertAsync(
        Stream source, string sourceExtension, ConversionTarget target,
        string? password = null, CancellationToken ct = default);

    public Task<Stream> WordToHtmlAsync(string filePath, CancellationToken ct = default);

    public Task<Stream> HtmlToWordAsync(
        Stream htmlSource, ConversionTarget outputFormat = ConversionTarget.Docx,
        CancellationToken ct = default);
}

Resolved from DoconutHost.Services; the constructor is internal. sourceExtension includes the leading dot. HtmlToWordAsync writes a .doc file when outputFormat is ConversionTarget.Doc, and a .docx file for any other value.

ConversionTarget

The 45 output formats listed in Target formats.

ConverterWidgetOptions

csharp
public sealed class ConverterWidgetOptions
{
    public int MaxUploadMb { get; set; } = 25;
}

Set through DoconutOptions.AddConverterWidget(Action<ConverterWidgetOptions>? configure = null), which returns the DoconutOptions so calls can be chained.

Troubleshooting

SymptomCauseFix
Every request answers an empty 500 after adding the plugin; the Windows event log (source ASP.NET) shows The Converter plugin is registered via AddPlugin but no active license grants Converter.No license, a TRIAL file, a license without Converter, or a paid license outside its version windowInstall a license that grants Converter, or remove AddPlugin<ConverterPlugin>()
Every request answers an empty 500; the event log shows AddConverterWidget() was called but the Converter plugin is not registered.The widget is enabled without its pluginAdd options.AddPlugin<Doconut.Plugins.Converter.ConverterPlugin>()
Resolving DocumentConverter throws No IDocumentConverter is registered. Add the converter plugin: options.AddPlugin<Doconut.Plugins.Converter.ConverterPlugin>().ConverterPlugin is not registeredAdd AddPlugin<ConverterPlugin>() in DoconutHost.Initialize
A Web Forms conversion never returnsThe page blocks on ConvertAsyncUse Async="true" and RegisterAsyncTask
Stream conversion says the format is unsupportedsourceExtension has no leading dotPass ".xlsx", not "xlsx"
ConvertAsync throws Converting '.dcm' requires the Dicom capability license.A DICOM source, and the license does not grant DicomUse a license that grants Dicom
The output is watermarkedThe license is temporary (Demo/NFR)Use a paid license that grants Converter
The widget loads but its requests return 404AddConverterWidget() was not called, or basePath is not '/DocImage.axd'Call AddConverterWidget(); set basePath: '/DocImage.axd'
A large upload shows an IIS error page instead of the widget's messagemaxRequestLength / maxAllowedContentLength are below MaxUploadMbRaise the Web.config limits above MaxUploadMb
open answers 403 Converting this file type requires the Dicom capability license.A DICOM upload, and the license does not grant DicomUse a license that grants Dicom
run answers 400 That target format is not available for this file.The target is not one of the source's allowedTargetsOffer only the allowedTargets from convert=open
run or download answers 404 (Upload expired — please re-open the file. from run)The 30-minute window elapsed, or another server in a farm does not have the uploadOpen the file again; in a farm, register AddDoconutDistributedWidgets
The widget fails when the UI is on another originThe endpoints have no CORS supportServe the UI from the same origin, or reverse-proxy the Doconut paths
The theme does not applyThe variables are set on an ancestor or on an element inside the mount; the widget's own .dcw rule sets them on the mountTarget the mount itself: #doconut-convert.dcw or #doconut-convert

Framework notes

Compared with the ASP.NET Core packages, this package differs in hosting only; the API, the endpoint contract, the widget script and the licensing rules are the same.

  • Registration is in Application_Start, through DoconutHost.Initialize, instead of builder.Services.AddDoconut. Services such as AddDoconutDistributedWidgets go in its second argument.
  • Endpoints are served by DocImage.axd and the script by DoconutResourceModule, both registered in Web.config, instead of UseDoconut() and UseDoconutResources(). The widget needs basePath: '/DocImage.axd'.
  • Startup failures surface as an empty 500 on every request, with the reason in the Windows event log.
  • Uploads are read in full by ASP.NET before Doconut sees them, so the IIS limits must be above MaxUploadMb.
  • Web Forms pages must not block on a conversion; see In Web Forms.
  • Windows only, like the rest of the .NET Framework package.

Was this page helpful?