Signer Plugin

Sign PDF and Word documents with a visible signature and a digital seal

The Signer plugin places a visible signature on a document and, by default, seals it with a digital signature that a PDF reader can verify. It signs PDF and Word (.docx) files. The visible signature is always a PNG image: drawn, typed, or uploaded by the signer.

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

Each signature is placed once, on one page. The signer's name, the reason and the location can travel with it.

Install the package

powershell
Install-Package Doconut.NETFramework.Signer

To pin the plugin to the release this documentation describes:

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

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

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

Register the plugin

Like every Doconut plugin, Signer registers with 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.Signer.SignerPlugin>();
});

Add Doconut.DoconutHost.Shutdown() to Application_End so background work stops cleanly when the app pool recycles.

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

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

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

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 Signer, and a paid license used outside its version window. Temporary Demo/NFR licenses are accepted. See License Setup.

Licensing & watermark

License stateStartupCertified signatureVisual signature
Paid license granting Signer, certificate configuredStartsSealed with your certificate, clean (watermarked: false)Clean
Paid license granting Signer, no certificateStartsRefused: No signing certificate configured.Clean
Paid license, certificate expired or not yet validStartsRefused: The signing certificate expired on yyyy-MM-dd.Clean
Temporary Demo/NFR license, active or expiredStartsSealed with the built-in demo certificate, watermarked (watermarked: true)Watermarked
No license, a legacy TRIAL file, a license without Signer, or a paid license outside its version windowApplication_Start throws; every request answers an empty 500——

The rule is the same for the C# facade and the widget: output is watermarked when the license is not a paid viewer license or is temporary. Under a temporary license the plugin always signs with its built-in demo certificate, and any certificate you configure is not used.

The demo certificate produces a genuine seal, but PDF readers do not trust it. An integration can be built and tested end to end on an evaluation license; to get clean, trusted output you need both a paid license and your own signing certificate.

Use from C#

DocumentSigner is registered by DoconutHost.Initialize; resolve it from DoconutHost.Services. Its constructor is internal, so never new it. Resolving it without AddPlugin<SignerPlugin>() throws No IDocumentSigner is registered. Add the signing plugin: options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>().

csharp
using Doconut;
using Doconut.Core.Models.Signing;

public sealed class ContractSigning
{
    private readonly DocumentSigner _signer;

    public ContractSigning(DocumentSigner signer) => _signer = signer;

    public async Task<byte[]> SignAsync(Stream pdf, byte[] signaturePng, SigningCertificate certificate, CancellationToken ct)
    {
        var request = new SignRequest(
            new VisibleSignature(SignatureKind.Drawn, signaturePng),
            new SignaturePlacement(Page: 1, X: 0.58, Y: 0.80, W: 0.32, H: 0.12),
            SignerName: "Ada Lovelace",
            Reason: "I approve this document",
            Location: "London, UK");
        // Mode defaults to Certified (visible signature + digital seal); WordOutput defaults to Pdf.

        SignResult result = await _signer.SignAsync(pdf, ".pdf", request, certificate, ct);
        using (result.Stream)
        using (var output = new MemoryStream())
        {
            await result.Stream.CopyToAsync(output, 81920, ct);
            return output.ToArray();
        }
    }
}

SignAsync takes the source stream, its extension (".pdf" or ".docx"), the request, and the certificate for this call. The facade does not read SignerWidgetOptions.SigningCertificate; that setting is for the widget. Pass null under a demo license, or in Visual mode.

SignResult holds the signed document as a seekable stream, plus its Extension (".pdf" or ".docx") so you can name the file. You own the stream: dispose it when you are done.

In an MVC 5 controller

Make the action asynchronous and await the signature. This one stamps a Visual signature, which needs no certificate:

csharp
[HttpPost]
public async Task<ActionResult> Sign(HttpPostedFileBase file)
{
    var signer = Doconut.DoconutHost.Services.GetRequiredService<DocumentSigner>();
    byte[] signaturePng = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/signature.png"));

    var request = new SignRequest(
        new VisibleSignature(SignatureKind.Image, signaturePng),
        new SignaturePlacement(Page: 1, X: 0.58, Y: 0.80, W: 0.32, H: 0.12),
        Mode: SignatureMode.Visual);

    SignResult result = await signer.SignAsync(
        file.InputStream, Path.GetExtension(file.FileName), request, ct: Response.ClientDisconnectedToken);
    string contentType = result.Extension == ".pdf"
        ? "application/pdf"
        : "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    return File(result.Stream, contentType, Path.GetFileNameWithoutExtension(file.FileName) + "-signed" + result.Extension);
}

A Word source is signed to PDF unless you ask for Word output. Name the result from result.Extension:

csharp
var signer = Doconut.DoconutHost.Services.GetRequiredService<DocumentSigner>();
byte[] signaturePng = File.ReadAllBytes(HostingEnvironment.MapPath("~/App_Data/signature.png"));

var request = new SignRequest(
    new VisibleSignature(SignatureKind.Drawn, signaturePng),
    new SignaturePlacement(Page: 1, X: 0.58, Y: 0.80, W: 0.32, H: 0.12),
    WordOutput: WordOutput.Docx);

SignResult result = await signer.SignAsync(stream, ".docx", request, ct: ct);
string downloadName = "contract-signed" + result.Extension;   // ".docx"

SignAsync throws instead of returning when the call cannot succeed:

ExceptionMessageWhen
InvalidOperationExceptionNo signing certificate configured.Certified mode, a paid license, and no certificate passed
InvalidOperationExceptionThe signing certificate expired on yyyy-MM-dd. / The signing certificate is not valid before yyyy-MM-dd.Certified mode with a certificate outside its validity window
ArgumentExceptionThe sign request is invalid: the visible signature needs PNG bytes and the placement must be a normalized rectangle on a 1-based page.Empty PNG bytes, or a placement that is not valid
NotSupportedExceptionThe signer supports PDF and Word (.docx) documents; got '{extension}'.Any other source type

Signing modes, Word output and certificates

Signing modes

SignRequest.Mode chooses whether the signature is sealed.

ModeWhat it producesCertificateVerifiable
SignatureMode.Certified (default)The visible signature plus a digital sealRequired under a paid licenseYes
SignatureMode.VisualThe visible signature onlyNever neededNo: it is a picture

Use Certified when the signature must be provable: approvals, contracts, anything a verifier needs to check for identity and integrity. Use Visual when you only need the appearance of a signature, or have no certificate. A temporary license watermarks both.

PDF seals are PKCS#7 detached signatures (adbe.pkcs7.detached) with SHA-256, for RSA or ECDSA keys. They carry the issuer certificates found in your PFX, so a reader that trusts your root can build the chain. Word-native seals are OOXML package signatures and carry the signer certificate only.

Word documents

For a .docx source, SignRequest.WordOutput chooses the output. It is ignored for PDF sources, which always produce a PDF.

OutputWhat happensVerifier support
WordOutput.Pdf (default)The document is converted to PDF, then signed and sealedBroad: a signed PDF verifies everywhere
WordOutput.DocxThe document stays Word: the signature image is placed in it, plus an OOXML package signatureLimited: not every viewer shows OOXML package signatures

Keep PDF unless the recipient needs an editable Word file and accepts the limited verifier support.

Certificate setup

To seal with your own identity, give the plugin a PFX (PKCS#12) file that includes the private key. For the widget, set SignerWidgetOptions.SigningCertificate; for the C# facade, pass the certificate to SignAsync. Provide either the bytes or a path, plus the password. App_Data is a good place for the file, because IIS never serves it:

csharp
Doconut.DoconutHost.Initialize(options =>
{
    options.LicensePath = HostingEnvironment.MapPath("~/wwwroot/Doconut.Viewer.lic");
    options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>();
    options.AddSignerWidget(widget =>
    {
        widget.SigningCertificate = new SigningCertificate
        {
            PfxBytes = File.ReadAllBytes(HostingEnvironment.MapPath("~/App_Data/signing.pfx")),
            Password = System.Configuration.ConfigurationManager.AppSettings["DoconutSigner:Password"] ?? "",
        };
    });
});
csharp
Doconut.DoconutHost.Initialize(options =>
{
    options.LicensePath = HostingEnvironment.MapPath("~/wwwroot/Doconut.Viewer.lic");
    options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>();
    options.AddSignerWidget(widget =>
    {
        widget.SigningCertificate = new SigningCertificate
        {
            PfxPath = HostingEnvironment.MapPath("~/App_Data/signing.pfx"),
            Password = System.Configuration.ConfigurationManager.AppSettings["DoconutSigner:Password"] ?? "",
        };
    });
});

SigningCertificate's properties are init-only, which C# 7.3 (the default for .NET Framework projects) cannot set. Set <LangVersion> to 9.0 or later in the project file.

The certificate is held in memory only. It is never logged, returned to a client, or persisted, and the password never appears in an error message.

Requirements:

  • A PFX / PKCS#12 bundle with its private key. A public-key-only file (.cer, .crt) cannot sign. Export the issuer chain with it, so PDF seals can carry it.
  • The correct password.
  • Inside its validity window. An expired or not-yet-valid certificate does not stop the app, but Certified signatures are refused until it is replaced. Visual signatures are unaffected.
  • Issued for document signing: a key usage with digital signature or non-repudiation, and an extended key usage, if present, that allows document signing, e-mail protection or client authentication. A certificate issued for something else, such as a TLS server certificate, still signs, but PDF readers flag the signature.
  • Hardware tokens, smart cards, HSMs and the Windows certificate store are not supported. Export the certificate, with its private key and chain, to a PFX.

Create a PFX from a certificate and its private key with OpenSSL:

bash
openssl pkcs12 -export -out signing.pfx -inkey private.key -in certificate.crt
# The export password you are prompted for is SigningCertificate.Password.

Export one from the Windows certificate store: open certmgr.msc and find the certificate (its icon shows a key when the private key is present). Right-click it, choose All Tasks → Export…, select Yes, export the private key, choose Personal Information Exchange – PKCS #12 (.PFX), and set a password.

Startup checks

When the widget is enabled, the certificate in SignerWidgetOptions.SigningCertificate is checked once, inside DoconutHost.Initialize, so a misconfigured PFX fails at startup rather than on the first signature. Three problems throw an InvalidOperationException from Application_Start, and every request then answers an empty 500; the message is in the Windows event log:

MessageFix
Doconut Signer: the certificate file was not found at '{path}'.Correct PfxPath; make sure the file is deployed and readable by the app pool's account
Doconut Signer: the signing certificate could not be opened — the password is incorrect or the file is not a valid .pfx.Check the password; make sure the file is a real .pfx, not a .cer or .pem
Doconut Signer: the signing certificate has no private key. Re-export the .pfx INCLUDING the private key.Export the PFX again with the private key

On ASP.NET Core the host also logs one line at startup naming the certificate, or warning that it is expired or not issued for signing. DoconutHost does not write that line, so on .NET Framework check a new certificate by signing a test document in Certified mode.

The C# facade is not checked at startup. The certificate you pass to SignAsync is read when you sign, so a wrong path or password fails that call.

Drop-in widget

Enable the endpoints

The widget's ?sign=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.Signer.SignerPlugin>();
    options.AddSignerWidget(widget =>
    {
        widget.MaxUploadMb = 25;           // the default
        widget.MaxSignatureImageKb = 512;  // the default
        // widget.SigningCertificate: see Certificate setup; leave it null for demo (watermarked) signing
    });
});
// System.Web reads the whole upload before Doconut sees it: keep maxRequestLength (KB) and
// maxAllowedContentLength (bytes) in Web.config above the widget's MaxUploadMb.

AddSignerWidget() with no argument enables the widget with the defaults. It does not grant signing by itself: it needs AddPlugin<SignerPlugin>(), or DoconutHost.Initialize throws:

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

The endpoints and the script are served by the handler and the module registered in Web.config:

xml
<system.webServer>
  <handlers>
    <add name="DocImage" verb="GET,HEAD,POST" path="DocImage.axd" type="Doconut.DocImageHandler, Doconut" />
  </handlers>
  <modules>
    <add name="DoconutResources" type="Doconut.DoconutResourceModule, Doconut" />
  </modules>
</system.webServer>

The module serves the script whether or not the widget is enabled. Without AddSignerWidget(), the widget loads and paints its drop zone, and its first request answers 404: the widget then reports Signing is not enabled on this server.

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 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>

An upload sent without a Content-Length (chunked) that exceeds the host limits also gets the IIS error page; there is no workaround for that case.

Embed it

The script is served at /doconut-res/js/doconutSigner.js. It is a single, self-contained file with no dependencies. Point basePath at the handler:

html
<div id="host"></div>
<script src="/doconut-res/js/doconutSigner.js"></script>
<script>
  const handle = Doconut.signer('#host', { basePath: '/DocImage.axd' });
</script>

Doconut.signer(selectorOrElement, options) takes a CSS selector or an element, throws if the mount is not found, and returns a handle. The widget's default basePath, /doconut, is the ASP.NET Core endpoint; on this package it must be '/DocImage.axd'.

The signer uploads a PDF or .docx file, builds a signature (Draw on a canvas, Type a name in a signature font, or Image from a PNG, JPG or GIF), drags and resizes it onto the page, and signs and downloads the result. The widget always sends the signature as a PNG; an uploaded image is converted in the browser to a PNG that fits 520×160.

Options

OptionTypeDefaultNotes
basePathstring'/doconut'Where the ?sign= endpoints and preview images are served. Set '/DocImage.axd' on this package
resPathstring'/doconut-res'Reserved; the widget bundles its own CSS
maxUploadMbnumber25Client-side check only, so an oversized file fails fast. The server cap is MaxUploadMb in AddSignerWidget
maxSignatureKbnumber512Client-side cap for the Image mode. Keep it equal to the server's MaxSignatureImageKb
previewWidthnumber560Pixel width of the page preview
licenseUrlstring | nullnullTurns the demo-watermark notice into a link to this URL
signatureModestring'certified'Initial signature type: 'certified' or 'visual'. Any other value becomes 'certified'
showSignatureModeTogglebooleantrueShows the Digital signature / Visual only choice. With false, the widget signs with signatureMode
wordOutputstring'pdf'Initial output for .docx sources: 'pdf' or 'docx'. Any other value becomes 'pdf'
showOutputFormatTogglebooleantrueShows the PDF / Word choice, for .docx sources only. With false, the widget uses wordOutput
labelsobject{}Overrides any subset of the English strings

Hiding a toggle does not disable the feature; it fixes the value. Two common configurations:

javascript
// Both toggles shown, digital signature by default: a full self-service signer.
Doconut.signer('#host', { basePath: '/DocImage.axd', licenseUrl: '/pricing' });
javascript
// Visual only, no toggle: a simple stamp with no digital signature offered.
Doconut.signer('#host', {
  basePath: '/DocImage.axd',
  signatureMode: 'visual',
  showSignatureModeToggle: false
});

Callbacks

CallbackFires whenPayload
onReadyOnce, at mount (not again on reset())—
onSourceLoadedThe file is opened and its preview shown{ file: { token, name, pages, ext } }
onSignedSigning succeeds{ downloadToken, downloadName, watermarked }
onDownloadOn each Download click{ downloadName, downloadToken }
onErrorAn open, sign or download step fails, or an Image-mode file is too large{ message }

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

Imperative handle

MethodBehavior
reset()Returns to the drop screen and clears the current flow. Does not fire onReady again. No-op after destroy()
loadFile(file)Starts the flow with a File. No-op unless the widget is at its drop screen; call reset() first if needed
destroy()Removes the listeners, empties the mount, and freezes the instance
javascript
const signerWidget = Doconut.signer('#host', {
  basePath: '/DocImage.axd',
  onSigned: (result) => console.log('signed', result.downloadName, result.watermarked),
  onError: (error) => console.warn(error.message)
});
document.getElementById('start-over').addEventListener('click', () => signerWidget.reset());

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 PDF or Word file here
dropHintPDF or Word (.docx)
chooseFileChoose file
signatureHeadingYour signature
modeDraw / modeType / modeImageDraw / Type / Image
metaSummarySignature details (optional)
metaSignerName / metaReason / metaLocationSigner name / Reason / Location
signatureTypeSignature type
modeCertified / modeVisualDigital signature / Visual only
modeVisualNoteNo certificate — a visible mark only, not cryptographically verifiable.
outputFormatOutput format
outputPdf / outputWordPDF / Word (.docx)
signActionSign document
downloadDownload
demoNoticeDemo — signed with the Doconut demo certificate; output is watermarked.
signingNotEnabledSigning is not enabled on this server.
page / pages1 page / {n} pages

Further keys cover the placement step, the error screen, the linked form of the demo notice (demoNoticePrefix, demoNoticeLink, demoNoticeSuffix) and the aria-live announcements.

When open or run answers 404 with no JSON error, the widget shows signingNotEnabled. A JSON error from the server always wins, so messages such as an expired upload stay visible.

Theming

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

css
#host.dsw {
  --dsw-accent: #b0522b;       /* links, focus, active mode */
  --dsw-bg: #fffaf3;
  --dsw-fg: #3b2a1a;
  --dsw-muted: #8a7a68;
  --dsw-border: #e0cbb0;
  --dsw-radius: 14px;
  --dsw-font: Georgia, "Times New Roman", serif;
  --dsw-signature-font: "Segoe Script", "Brush Script MT", cursive;   /* the Type mode */
}

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

Build your own frontend

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

RoutePurposeSuccess response
POST /DocImage.axd?sign=open (multipart, one file)Upload a PDF or .docx and open it for preview200 — { token, name, pages, ext }
POST /DocImage.axd?sign=run (JSON body)Sign the uploaded file200 — { downloadToken, downloadName, watermarked }
GET /DocImage.axd?sign=download&token=<downloadToken>Stream the signed file200 — the file, Content-Disposition: attachment, Cache-Control: no-store

ext in the open response includes the leading dot (".docx"). The page preview uses the standard viewer image route, /DocImage.axd?token={token}&page={n}&thumb=1&width={px}; the page shown becomes placement.page.

The run body:

json
{
  "token": "GUID-from-open",
  "signature": { "kind": "Drawn", "payload": "<base64 PNG, no data: prefix>" },
  "placement": { "page": 1, "x": 0.58, "y": 0.80, "w": 0.32, "h": 0.12 },
  "meta": { "signerName": "Ada Lovelace", "reason": "I approve", "location": "London, UK" },
  "wordOutput": "pdf",
  "mode": "certified"
}
FieldNotes
tokenThe token from open
signature.kindDrawn, Typed or Image, case-insensitive; anything else becomes Drawn. A hint only: the payload is always a PNG
signature.payloadA bare base64 PNG, with no data: prefix. It must be a real PNG and no larger than MaxSignatureImageKb once decoded
placement.page1-based
placement.x / y / w / hNormalized 0..1 from the top-left corner, with x + w ≤ 1 and y + h ≤ 1
meta.signerName / reason / locationOptional. Each is trimmed, a blank value is dropped, and each is cut at 256 characters
wordOutputpdf (default) or docx; ignored for PDF sources. Anything else becomes pdf
modecertified (default) or visual. Anything else becomes certified

downloadName follows the output: <source>-signed.pdf or <source>-signed.docx, and download sends the matching Content-Type.

The uploaded source and the signed result are each kept for 30 minutes. After that, run and download answer 404 and the file must be opened again. All tokens are GUIDs.

RouteStatusWhenBody
any404The widget is not enabledstatus only
any405Wrong verb (open and run need POST, download needs GET)status only
open400Not a multipart uploadExpected a multipart file upload.
open400No file, or an empty oneNo file uploaded.
open400Anything other than .pdf or .docxSigning supports PDF and Word (.docx) files only.
open413The upload exceeds MaxUploadMb (but not the IIS limits)File is too large.
run400The body is not valid JSON, or is emptyMalformed request. / Empty request.
run400The token is missing or not a GUIDInvalid token.
run404The upload expired or was never openedUpload expired — please re-open the file.
run400No signature, or no placementNo signature supplied. / No placement supplied.
run400The payload is not base64, is empty, too large, or not a PNGSignature image is not valid base64. / Signature image is empty. / Signature image is too large. / The signature image must be a PNG.
run400The placement is outside the pageThe signature or its placement is invalid.
run400Certified mode, a paid license and no certificateNo signing certificate configured.
run400Certified mode with a certificate outside its validity windowThe signing certificate expired on yyyy-MM-dd. / The signing certificate is not valid before yyyy-MM-dd.
open, run500Processing failedA sanitized message
download400The token is missing or not a GUIDstatus only
download404Unknown or expired tokenstatus only

A complete round trip with fetch:

javascript
// file: the File to sign; pngBase64: the signature as a bare base64 PNG, with no data: prefix,
// for example canvas.toDataURL('image/png').split(',')[1].
async function signFile(file, pngBase64) {
  const base = '/DocImage.axd';

  // 1. open: upload the file
  const form = new FormData();
  form.append('file', file, file.name);
  const opened = await (await fetch(base + '?sign=open', { method: 'POST', body: form })).json();

  // 2. run: sign it
  const signed = await (await fetch(base + '?sign=run', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      token: opened.token,
      signature: { kind: 'Drawn', payload: pngBase64 },
      placement: { page: 1, x: 0.58, y: 0.80, w: 0.32, h: 0.12 },
      meta: { signerName: 'Ada Lovelace', reason: 'I approve', location: 'London, UK' },
      wordOutput: 'pdf',
      mode: 'certified'
    })
  })).json();

  // 3. download: fetch the signed file
  const blob = await (await fetch(base + '?sign=download&token=' + encodeURIComponent(signed.downloadToken))).blob();
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = signed.downloadName;
  link.click();
  URL.revokeObjectURL(link.href);
}

The endpoints are same-origin: this version has no CORS support. Serve your UI and the widget script from the same origin as the application, or reverse-proxy DocImage.axd and /doconut-res under your UI's origin.

In production

  1. Install the plugin next to the core package, at the same version: Install-Package Doconut.NETFramework.Signer.

  2. Add the license file. Put Doconut.Viewer.Signer.lic in the same folder as Doconut.Viewer.lic.

  3. Get your certificate as a PFX with its private key and issuer chain, from a certificate authority or your organization's own PKI. To try things first, use a demo license (the built-in demo certificate, watermarked) or a self-signed PFX.

  4. Read the certificate from configuration, so changing it never needs a code change:

    xml
    <appSettings>
      <add key="DoconutSigner:PfxPath" value="~/App_Data/your-certificate.pfx" />
    </appSettings>
    csharp
    var settings = System.Configuration.ConfigurationManager.AppSettings;
    
    Doconut.DoconutHost.Initialize(options =>
    {
        options.LicensePath = HostingEnvironment.MapPath("~/wwwroot/Doconut.Viewer.lic");
        options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>();
        options.AddSignerWidget(widget => widget.SigningCertificate = new SigningCertificate
        {
            PfxPath = HostingEnvironment.MapPath(settings["DoconutSigner:PfxPath"]),
            Password = settings["DoconutSigner:Password"] ?? "",
        });
    });

    Keep the .pfx in App_Data, which IIS never serves, and keep the password out of a plain Web.config: use an encrypted configuration section, or a secret store your deployment reads.

  5. Sign a test document in Certified mode. A certificate that is expired or not yet valid is refused with The signing certificate expired on yyyy-MM-dd. (or is not valid before), and a PDF reader shows whether it trusts the signature.

Trust in PDF readers. A reader shows the signature as valid when it trusts the certificate's root. With your organization's PKI, that holds on every machine that trusts your root, which is usually every machine inside the organization. Certificates that Adobe trusts on any machine (the Adobe Approved Trust List) are, as far as we know, issued with the private key on a hardware token or HSM, which this plugin cannot use: it signs from a PFX only. Confirm with your certificate provider before relying on that kind of trust.

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.Signer.SignerPlugin>();
        options.AddSignerWidget();
    },
    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.
  • 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, and give every server the same signing certificate.

API reference

The facade and the widget options are in the Doconut namespace; the request and result types are in Doconut.Core.Models.Signing. SignerPlugin is in Doconut.Plugins.Signer.

DocumentSigner

csharp
public sealed class DocumentSigner
{
    public Task<SignResult> SignAsync(
        Stream source, string sourceExtension, SignRequest request,
        SigningCertificate? cert = null, CancellationToken ct = default);
}

Resolved from DoconutHost.Services; the constructor is internal. sourceExtension is ".pdf" or ".docx". Under a paid license cert is used and the output is clean; under a temporary license the built-in demo certificate is used, cert is ignored, and the output is watermarked.

SignRequest

csharp
public sealed record SignRequest(
    VisibleSignature   Signature,
    SignaturePlacement Placement,
    string?            SignerName = null,
    string?            Reason     = null,
    string?            Location   = null,
    WordOutput         WordOutput = WordOutput.Pdf,
    SignatureMode      Mode       = SignatureMode.Certified)
{
    public bool IsValid { get; }   // Signature.IsValid && Placement.IsValid
}

One visible signature placed once, plus optional signer metadata.

VisibleSignature and SignatureKind

csharp
public sealed record VisibleSignature(SignatureKind Kind, byte[] PngBytes)
{
    public bool IsValid { get; }   // PngBytes is not empty
}

public enum SignatureKind { Drawn, Typed, Image }

PngBytes is a PNG for every kind. A drawn or typed signature is transparent; an uploaded image keeps the transparency it had, so an opaque JPG stays opaque. Kind is a hint only.

SignaturePlacement

csharp
public readonly record struct SignaturePlacement(int Page, double X, double Y, double W, double H)
{
    public bool IsValid { get; }   // Page >= 1; X, Y >= 0; W, H > 0; X + W <= 1; Y + H <= 1
}

Page is 1-based; X, Y, W and H are normalized 0..1 from the top-left corner.

SignatureMode and WordOutput

csharp
public enum SignatureMode { Certified, Visual }   // Certified is the default
public enum WordOutput { Pdf, Docx }              // Pdf is the default; ignored for PDF sources

SignResult

csharp
public sealed record SignResult(Stream Stream, string Extension);

The signed document as a seekable stream, and its extension with the dot (".pdf" or ".docx").

SigningCertificate

csharp
public sealed class SigningCertificate
{
    public byte[]? PfxBytes { get; init; }
    public string? PfxPath  { get; init; }
    public string  Password { get; init; } = "";
    public bool    HasMaterial { get; }   // PfxBytes is not empty, or PfxPath is not blank
}

Set either PfxBytes or PfxPath, plus Password. The setters are init-only: the project needs C# 9.0 or later.

SignerWidgetOptions

csharp
public sealed class SignerWidgetOptions
{
    public int MaxUploadMb { get; set; } = 25;
    public int MaxSignatureImageKb { get; set; } = 512;
    public SigningCertificate? SigningCertificate { get; set; }
}

Set through DoconutOptions.AddSignerWidget(Action<SignerWidgetOptions>? configure = null), which returns the DoconutOptions so calls can be chained. A null SigningCertificate means the demo certificate under a temporary license, and Visual signatures only under a paid one.

Troubleshooting

SymptomCauseFix
Every request answers an empty 500 after adding the plugin; the event log shows The Signer plugin is registered via AddPlugin but no active license grants Signer.No license, a TRIAL file, a license without Signer, or a paid license outside its version windowInstall a license that grants Signer, or remove AddPlugin<SignerPlugin>()
The event log shows AddSignerWidget() was called but the Signer plugin is not registered.The widget is enabled without its pluginAdd options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>()
The event log shows Doconut Signer: the certificate file was not found at '{path}'.PfxPath points at a missing fileFix the path; deploy the file where the app pool's account can read it
The event log shows Doconut Signer: the signing certificate could not be opened — the password is incorrect or the file is not a valid .pfx.Wrong password, or not a PKCS#12 fileCheck the password; use a real .pfx
The event log shows Doconut Signer: the signing certificate has no private key. Re-export the .pfx INCLUDING the private key.The PFX was exported without its private keyExport it again with the private key
new SigningCertificate { … } does not compileThe project uses C# 7.3, which cannot set init-only propertiesSet <LangVersion> to 9.0 or later
Resolving DocumentSigner throws No IDocumentSigner is registered.SignerPlugin is not registeredAdd AddPlugin<SignerPlugin>() in DoconutHost.Initialize
The output is watermarkedThe license is temporary (Demo/NFR)Use a paid license that grants Signer
run answers 400 No signing certificate configured.A paid license, Certified mode, and no certificateConfigure SigningCertificate, or sign in Visual mode
run answers 400 The signing certificate expired on yyyy-MM-dd.The certificate is out of dateReplace it; Visual signatures keep working meanwhile
The widget loads but says Signing is not enabled on this server.AddSignerWidget() was not called, or basePath is not '/DocImage.axd'Call AddSignerWidget(); set basePath: '/DocImage.axd'
A large upload shows an IIS error page instead of the widget's messagemaxRequestLength / maxAllowedContentLength are below MaxUploadMbRaise both host limits above MaxUploadMb
run answers 400 The signature image must be a PNG., Signature image is not valid base64. or Signature image is too large.A custom UI sent a data: URL, a JPG, or more than MaxSignatureImageKbSend a bare base64 PNG within the cap
open answers 413 File is too large.The upload exceeds MaxUploadMbRaise MaxUploadMb in AddSignerWidget; the widget's maxUploadMb is only a client-side check
run or download answers 404 Upload expired — please re-open the file.The 30-minute window elapsed, or another server in the farm does not have the uploadOpen the file again; in a farm, register AddDoconutDistributedWidgets
A signed .docx shows no signature in some viewersWord output carries an OOXML package signature, which many viewers do not showSign to PDF, the default
PDF readers say the signer's identity is unknownThe reader does not trust the certificate's root (the demo certificate is never trusted)Use a certificate from a root your readers trust
The widget fails when the UI is on another originThe endpoints have no CORS supportServe the UI from the same origin, or reverse-proxy DocImage.axd and /doconut-res
The theme does not applyThe selector targets an element inside the mountTarget the mount itself: #host.dsw or #host

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.
  • No startup log line about the certificate: the three certificate errors still throw, but the line naming the certificate is not written.
  • C# 9.0 or later is needed to set SigningCertificate's init-only properties.
  • Windows only, like the rest of the .NET Framework package.

Was this page helpful?