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.
| Surface | Use 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
Install-Package Doconut.NETFramework.ConverterTo pin the plugin to the release this documentation describes:
Install-Package Doconut.NETFramework.Converter -Version 26.10.0Keep 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.
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:
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 state | Startup | Conversion output |
|---|---|---|
Paid viewer license granting Converter, within its version window | Starts | Clean — watermarked: false |
| Active Temporary (Demo/NFR) license | Starts | Converts, with the evaluation watermark — watermarked: true |
| Expired Temporary (Demo/NFR) license | Starts | Converts, with the evaluation watermark — watermarked: true |
No license, a legacy TRIAL file, a license without Converter, or a paid license outside its version window | Application_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.
// Resolve DocumentConverter from DoconutHost.Services; its constructor is internal, so never `new` it.
Stream pdf = await converter.ConvertAsync("contract.docx", ConversionTarget.Pdf, ct: ct);// 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);Stream html = await converter.WordToHtmlAsync("report.docx", ct);// 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:
[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:
<%@ Page Language="C#" Async="true" CodeBehind="Convert.aspx.cs" Inherits="MyApp.Convert" %>// 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:
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, IcoNot 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:
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:
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 theDocImage.axdhandler fromWeb.config.- The script and the endpoints are independent. The resource module serves
doconutConverter.jswhether or not the widget is enabled. WithoutAddConverterWidget(), the widget loads, paints its drop zone, and looks entirely correct — and its first action answers404.
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:
<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
<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
| Option | Type | Default | Notes |
|---|---|---|---|
basePath | string | /doconut | The endpoint URL. Set '/DocImage.axd' on this package |
resPath | string | /doconut-res | Accepted for consistency with other Doconut widgets; the converter widget does not build any URL from it |
maxUploadMb | number | 25 | Client-side pre-check only; the server enforces its own cap |
licenseUrl | string | null | null | Turns the watermark notice on the result screen into a link |
labels | object | {} | Overrides any subset of the widget's English strings |
Callbacks
| Callback | Fires when | Payload |
|---|---|---|
onReady() | The widget has rendered its drop screen | — |
onSourceLoaded({ token, pages, sourceExt, allowedTargets }) | ?convert=open succeeds | Source token, page count, source extension (no leading dot), allowed targets |
onConverted({ downloadToken, resultToken, resultPages, downloadName, watermarked, target }) | ?convert=run succeeds | The run response plus the requested target |
onDownload({ downloadName, downloadToken }) | The user clicks Download | Fires alongside the browser's own download |
onError({ phase, message }) | An open or run request fails | phase 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:
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 thisLabels
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'.
| Key | English default |
|---|---|
dropPrompt | Drag & drop a document here |
dropHint | PDF, Word, Excel, PowerPoint, images and more |
chooseFile | Choose file |
uploading | Uploading {name}… |
page / pages | 1 page / {n} pages |
noTargets | No conversion targets are available for this file. |
convertTo / convert | Convert to / Convert |
converting | Converting to {target}… |
readyToDownload | Ready to download |
download / convertAnother | Download / Convert another |
watermarkNotice | Output is watermarked — get a license to remove it. |
retry | Retry |
genericError | Something went wrong. Please try again. |
sizeLimit | That file is larger than the {mb} MB upload limit. Please choose a smaller file. |
serverError | The server could not process this request. Please try again. |
networkError | Could 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:
#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.
| Route | Purpose | Success response |
|---|---|---|
POST /DocImage.axd?convert=open (multipart, one file) | Upload and open a source document | 200 — { token, pages, sourceExt, allowedTargets } |
POST /DocImage.axd?token=<token>&convert=run&target=<ext> | Convert the uploaded source to target | 200 — { downloadToken, resultToken, resultPages, downloadName, watermarked } |
GET /DocImage.axd?convert=download&token=<downloadToken> | Stream the converted file | 200 — 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.
| Route | Status | When | Body |
|---|---|---|---|
| any | 404 | The widget isn't enabled (AddConverterWidget() was never called) | status only |
| any | 405 | Wrong verb (open/run require POST, download requires GET) | status only |
open | 400 | Not a multipart upload | Expected a multipart file upload. |
open | 400 | No file, or an empty one | No file uploaded. |
open | 400 | A type that cannot be converted | This file type cannot be converted. |
open | 403 | The file type needs a capability the license does not grant (a DICOM file without Dicom) | Converting this file type requires the Dicom capability license. |
open | 413 | The upload exceeds MaxUploadMb (but not the IIS limits) | File is too large. |
run | 400 | A malformed token (not a GUID) | Invalid token. |
run | 400 | A target that doesn't parse to a ConversionTarget | Unknown target format. |
run | 400 | A target not in allowedTargets | That target format is not available for this file. |
run | 404 | The upload expired or was never opened | Upload expired — please re-open the file. |
open, run | 500 | Processing failed | A sanitized message |
download | 400 / 404 | A malformed, unknown, or expired download token | status only |
A complete round trip with fetch:
// 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
- Install the plugin next to the core package, at the same version:
Install-Package Doconut.NETFramework.Converter. - Add the license file. Put
Doconut.Viewer.Converter.licin the same folder asDoconut.Viewer.lic. - Set the upload caps.
MaxUploadMbinAddConverterWidgetis the limit Doconut enforces; keepmaxRequestLengthandmaxAllowedContentLengthinWeb.configabove it (see Upload limits), and the widget'smaxUploadMbequal to it. - Never block on a conversion in Web Forms (see In Web Forms).
- Dispose conversion results. The stream
ConvertAsyncreturns 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:
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
Ttlafter it was written; reading it does not extend that window. FarmKeymust be at least 32 bytes and the same on every server. Load it from a secret store; never hard-code it. Registration throws anArgumentExceptionwhenRootPathis missing orFarmKeyis shorter than 32 bytes.- Point
RootPathat 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
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
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
| Symptom | Cause | Fix |
|---|---|---|
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 window | Install 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 plugin | Add 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 registered | Add AddPlugin<ConverterPlugin>() in DoconutHost.Initialize |
| A Web Forms conversion never returns | The page blocks on ConvertAsync | Use Async="true" and RegisterAsyncTask |
| Stream conversion says the format is unsupported | sourceExtension has no leading dot | Pass ".xlsx", not "xlsx" |
ConvertAsync throws Converting '.dcm' requires the Dicom capability license. | A DICOM source, and the license does not grant Dicom | Use a license that grants Dicom |
| The output is watermarked | The license is temporary (Demo/NFR) | Use a paid license that grants Converter |
The widget loads but its requests return 404 | AddConverterWidget() 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 message | maxRequestLength / maxAllowedContentLength are below MaxUploadMb | Raise 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 Dicom | Use 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 allowedTargets | Offer 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 upload | Open the file again; in a farm, register AddDoconutDistributedWidgets |
| The widget fails when the UI is on another origin | The endpoints have no CORS support | Serve the UI from the same origin, or reverse-proxy the Doconut paths |
| The theme does not apply | The variables are set on an ancestor or on an element inside the mount; the widget's own .dcw rule sets them on the mount | Target 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, throughDoconutHost.Initialize, instead ofbuilder.Services.AddDoconut. Services such asAddDoconutDistributedWidgetsgo in its second argument. - Endpoints are served by
DocImage.axdand the script byDoconutResourceModule, both registered inWeb.config, instead ofUseDoconut()andUseDoconutResources(). The widget needsbasePath: '/DocImage.axd'. - Startup failures surface as an empty
500on 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?