签名插件
使用可见签名和数字印章对 PDF 和 Word 文档进行签署
Signer 插件在文档上放置可见签名,并默认使用 PDF 阅读器可验证的数字签名对其进行封印。它可以签署 PDF 和 Word (.docx) 文件。可见签名始终是 PNG 图像:由签署者绘制、键入或上传。
| 使用方式 | 适用场景 |
|---|---|
DocumentSigner (C#) | 在服务器上签署,不涉及浏览器 |
嵌入式小部件 (doconutSigner.js) | 您希望在页面中拥有现成的上传、签署和下载界面 |
在 DocImage.axd 上的 HTTP 端点 (?sign=open|run|download) | 您可以根据文档化的服务器合约自行构建签署 UI |
每个签名仅放置一次,位于单页上。签署者的姓名、原因和地点会随签名一起保存。
安装软件包
Install-Package Doconut.NETFramework.Signer将插件固定到本文档所描述的版本:
Install-Package Doconut.NETFramework.Signer -Version 26.10.0保持 Signer 包与 Doconut.NETFramework 的版本一致。
插件的许可证文件 Doconut.Viewer.Signer.lic 放在与 Doconut.Viewer.lic 相同的文件夹中;它会与查看器许可证一起读取。
注册插件
像所有 Doconut 插件一样,Signer 在 DoconutHost.Initialize 中使用 AddPlugin<TPlugin>() 注册,并由 Application_Start 调用:
Doconut.DoconutHost.Initialize(options =>
{
options.LicensePath = HostingEnvironment.MapPath("~/wwwroot/Doconut.Viewer.lic");
options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>();
});将 Doconut.DoconutHost.Shutdown() 添加到 Application_End,以便在应用池回收时后台工作能干净地停止。
这就是 C# 外观所需的全部。小部件及其 HTTP 端点是单独的可选功能,AddSignerWidget()(参见 嵌入式小部件)。
插件需要具备 Signer 功能的许可证。若没有许可证,DoconutHost.Initialize 会在 Application_Start 抛出异常:
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.在 System.Web 中,这意味着每个请求都会返回一个空的 500,原因仅记录在 Windows 事件日志(来源 ASP.NET)中。它会因缺少许可证、遗留的 TRIAL 文件、缺少 Signer 的许可证以及在版本窗口之外使用的付费许可证而抛出异常。临时演示/NFR 许可证已被接受。参见 许可证设置。
许可与水印
| 许可证状态 | 启动 | 认证签名 | 可视签名 |
|---|---|---|---|
付费许可证授予 Signer,已配置证书 | 启动 | 使用您的证书封印,干净(watermarked: false) | 干净 |
付费许可证授予 Signer,无证书 | 启动 | 拒绝:No signing certificate configured. | 干净 |
| 付费许可证,证书已过期或尚未生效 | 启动 | 拒绝:The signing certificate expired on yyyy-MM-dd. | 干净 |
| 临时演示/NFR 许可证,已激活或已过期 | 启动 | 使用内置演示证书封印,带水印(watermarked: true) | 带水印 |
无许可证、遗留的 TRIAL 文件、缺少 Signer 的许可证,或在版本窗口之外的付费许可证 | Application_Start 抛出异常;每个请求返回空的 500 | — | — |
规则对 C# 外观和小部件相同:当许可证不是付费查看器许可证或是临时许可证时,输出会带水印。在临时许可证下,插件始终使用内置的演示证书进行签署,您配置的任何证书都不会被使用。
演示证书会生成真实的印章,但 PDF 阅读器不信任它。可以在评估许可证上构建并端到端测试集成;若要获得干净、可信的输出,您需要付费许可证以及您自己的 签名证书。
在 C# 中使用
DocumentSigner 由 DoconutHost.Initialize 注册;从 DoconutHost.Services 解析它。它的构造函数是 internal 的,所以永远不要 new 它。没有 AddPlugin<SignerPlugin>() 就解析会抛出 No IDocumentSigner is registered. Add the signing plugin: options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>().
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 默认值为 Certified(可见签名 + 数字印章);WordOutput 默认值为 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 接受源流、它的扩展名(".pdf" 或 ".docx")、请求以及证书 此调用。Facade 不读取 SignerWidgetOptions.SigningCertificate;该设置用于小部件。使用演示许可证或 Visual 模式传递 null。
SignResult 将已签名的文档保存为可寻址的流,并附带其 Extension(".pdf" 或 ".docx"),以便您可以为文件命名。您拥有该流:使用完毕后请释放它。
在 MVC 5 控制器中
将操作设为异步并 await 签名。此操作会添加 Visual 签名,无需证书:
[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);
}Word 源文件默认签名为 PDF,除非您要求输出为 Word。使用 result.Extension 为结果命名:
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 在调用无法成功时会抛出异常,而不是返回:
| 异常 | 消息 | 何时 |
|---|---|---|
InvalidOperationException | No signing certificate configured. | 已认证模式、付费许可证且未传递证书 |
InvalidOperationException | The signing certificate expired on yyyy-MM-dd. / The signing certificate is not valid before yyyy-MM-dd. | 已认证模式下使用了超出有效期的证书 |
ArgumentException | The sign request is invalid: the visible signature needs PNG bytes and the placement must be a normalized rectangle on a 1-based page. | PNG 字节为空,或放置位置无效 |
NotSupportedException | The signer supports PDF and Word (.docx) documents; got '{extension}'. | 任何其他源类型 |
签名模式、Word 输出和证书
签名模式
SignRequest.Mode 选择签名是否被封存。
| 模式 | 生成内容 | 证书 | 可验证 |
|---|---|---|---|
SignatureMode.Certified(默认) | 可见签名加数字封章 | 付费许可证下必需 | 是 |
SignatureMode.Visual | 仅可见签名 | 从不需要 | 否:它是图片 |
使用 Certified 当签名必须可验证:批准、合同,任何验证者需要检查身份和完整性的情况。仅在只需要签名外观或没有证书时使用 Visual。临时许可证会在两者上添加水印。
PDF 封章是使用 SHA-256 的 PKCS#7 分离签名(adbe.pkcs7.detached),适用于 RSA 或 ECDSA 密钥。它们携带您 PFX 中的颁发者证书,因此信任您根证书的阅读器可以构建链。Word 原生封章是 OOXML 包签名,仅携带签署者证书。
Word 文档
对于 .docx 源,SignRequest.WordOutput 选择输出。对于 PDF 源会被忽略,始终生成 PDF。
| 输出 | 会发生什么 | 验证器支持 |
|---|---|---|
WordOutput.Pdf(默认) | 文档被转换为 PDF,然后签名并封存 | 广泛:签名的 PDF 在任何地方都能验证 |
WordOutput.Docx | 文档保持为 Word:在其中放置签名图像,并附加 OOXML 包签名 | 受限:并非所有查看器都显示 OOXML 包签名 |
除非收件人需要可编辑的 Word 文件并接受受限的验证器支持,否则保持使用 PDF。
证书设置
要使用您自己的身份进行封章,请为插件提供包含私钥的 PFX (PKCS#12) 文件。对于小部件,设置 SignerWidgetOptions.SigningCertificate;对于 C# 外观层,向 SignAsync 传递证书。提供字节或路径,加上密码。App_Data 是放置文件的好位置,因为 IIS 永不提供它:
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"] ?? "",
};
});
});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 的属性是 init-only,C# 7.3(.NET Framework 项目的默认版本)无法设置。将在项目文件中将 <LangVersion> 设置为 9.0 或更高版本。
证书仅保存在内存中。它从不被记录、返回给客户端或持久化,密码也永不出现在错误信息中。
要求:
- 一个 PFX / PKCS#12 捆绑包 包含私钥。仅公钥文件(
.cer、.crt)无法签名。请连同颁发者链一起导出,以便 PDF 封章能够携带它。 - 正确的密码。
- 在其 有效期窗口 内。已过期或尚未生效的证书不会阻止应用程序运行,但 Certified 签名会被拒绝,直至更换。Visual 签名不受影响。
- 用于文档签名:密钥用法包含 digital signature 或 non-repudiation,并且如果存在扩展密钥用法,则允许文档签名、电子邮件保护或客户端身份验证。若证书用于其他用途,例如 TLS 服务器证书,仍可签名,但 PDF 阅读器会标记该签名。
- 不支持硬件令牌、智能卡、HSM 和 Windows 证书存储。请将证书连同私钥和链导出为 PFX。
使用 OpenSSL 从证书及其私钥创建 PFX:
openssl pkcs12 -export -out signing.pfx -inkey private.key -in certificate.crt
# 导出密码提示您输入的是 SigningCertificate.Password。从 Windows 证书存储导出:打开 certmgr.msc 并找到证书(其图标在私钥存在时显示钥匙)。右键单击它,选择 所有任务 → 导出…,选择 是,导出私钥,选择 个人信息交换 – PKCS #12 (.PFX),并设置密码。
Startup checks
当小部件启用时,SignerWidgetOptions.SigningCertificate 中的证书会在 DoconutHost.Initialize 内检查一次,因此配置错误的 PFX 会在启动时失败,而不是在第一次签名时。三种问题会从 Application_Start 抛出 InvalidOperationException,随后每个请求都会返回空的 500;该消息记录在 Windows 事件日志中:
| Message | Fix |
|---|---|
Doconut Signer: the certificate file was not found at '{path}'. | 纠正 PfxPath;确保文件已部署且应用池账户可读取 |
Doconut Signer: the signing certificate could not be opened — the password is incorrect or the file is not a valid .pfx. | 检查密码;确保文件是真正的 .pfx,而不是 .cer 或 .pem |
Doconut Signer: the signing certificate has no private key. Re-export the .pfx INCLUDING the private key. | 使用私钥重新导出 PFX |
在 ASP.NET Core 上,主机在启动时也会记录一行包含证书名称的日志,或警告证书已过期或未用于签名。DoconutHost 不会写入该行,因此在 .NET Framework 上请通过在已认证模式下签署测试文档来检查新证书。
C# 外观在启动时不会被检查。您传递给 SignAsync 的证书会在签名时读取,因此路径或密码错误会导致该调用失败。
Drop-in widget
Enable the endpoints
小部件的 ?sign=open|run|download 端点由 DocImage.axd 提供,并且默认 off by default。在插件注册旁边启用它们:
Doconut.DoconutHost.Initialize(options =>
{
options.LicensePath = HostingEnvironment.MapPath("~/wwwroot/Doconut.Viewer.lic");
options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>();
options.AddSignerWidget(widget =>
{
widget.MaxUploadMb = 25; // 默认
widget.MaxSignatureImageKb = 512; // 默认
// widget.SigningCertificate: 请参阅 Certificate 设置;在演示(带水印)签名时保持为 null
});
});
// System.Web 在 Doconut 看到它之前读取整个上传:保持 maxRequestLength (KB) 和
// Web.config 中的 maxAllowedContentLength (bytes) 必须高于 widget 的 MaxUploadMb。AddSignerWidget() 在没有参数的情况下使用默认设置启用小部件。它本身并不授予签名权限:它需要 AddPlugin<SignerPlugin>(),否则 DoconutHost.Initialize 会抛出:
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.这些端点和脚本由处理程序以及在 Web.config 中注册的模块提供:
<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>无论小部件是否启用,模块都会提供脚本。若缺少 AddSignerWidget(),小部件仍会加载并绘制其拖放区,其首次请求会返回 404:随后小部件报告 Signing is not enabled on this server.
Upload limits
ASP.NET 在 DocImage.axd 运行之前会读取整个请求体。上传大小超过 MaxUploadMb 但低于主机限制时,会收到小部件自己的 JSON 413(File is too large.)。若上传超过主机限制,IIS 会先拒绝并返回错误页面,小部件无法读取。请确保主机的限制均高于小部件的上限:
<system.web>
<httpRuntime maxRequestLength="30720" /> <!-- 千字节: 30 MB -->
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="31457280" /> <!-- 字节: 30 MB -->
</requestFiltering>
</security>
</system.webServer>如果在没有 Content-Length(chunked)的情况下发送超过主机限制的上传,同样会收到 IIS 错误页面;此情况暂无解决办法。
嵌入它
脚本在 /doconut-res/js/doconutSigner.js 提供。它是一个单一的、独立的文件,没有任何依赖。将 basePath 指向处理程序:
<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) 接受一个 CSS 选择器或元素,如果未找到挂载点则抛出错误,并返回一个句柄。小部件的默认 basePath, /doconut 是 ASP.NET Core 端点;在此包中必须设为 '/DocImage.axd'。
签署者上传 PDF 或 .docx 文件,创建签名(绘制 在画布上,键入 签名字体的姓名,或 图片 来自 PNG、JPG 或 GIF),将其拖拽并调整大小放置在页面上,然后签署并下载结果。小部件始终以 PNG 形式发送签名;上传的图片会在浏览器中转换为符合 520×160 的 PNG。
选项
| 选项 | 类型 | 默认值 | 备注 |
|---|---|---|---|
basePath | string | '/doconut' | ?sign= 端点和预览图像的提供位置。请在此包上设置 '/DocImage.axd' |
resPath | string | '/doconut-res' | 保留;小部件自带其 CSS |
maxUploadMb | number | 25 | 仅客户端检查,因此超大文件会快速失败。服务器上限为 AddSignerWidget 中的 MaxUploadMb |
maxSignatureKb | number | 512 | Image 模式的客户端上限。保持与服务器的 MaxSignatureImageKb 相等 |
previewWidth | number | 560 | 页面预览的像素宽度 |
licenseUrl | string | null | null | 将演示水印通知转换为指向此 URL 的链接 |
signatureMode | string | 'certified' | 初始签名类型:'certified' 或 'visual'。任何其他值将变为 'certified' |
showSignatureModeToggle | boolean | true | 显示 数字签名 / 仅可视 选项。使用 false 时,小部件使用 signatureMode 进行签名 |
wordOutput | string | 'pdf' | .docx 源的初始输出:'pdf' 或 'docx'。任何其他值将变为 'pdf' |
showOutputFormatToggle | boolean | true | 显示 PDF / Word 选项,仅适用于 .docx 源。使用 false 时,小部件使用 wordOutput |
labels | object | {} | 覆盖任何英文字符串的子集 |
隐藏切换项不会禁用功能;它会固定该值。两种常见配置:
// 两个切换开关均显示,默认使用数字签名:完整的自助签署者。
Doconut.signer('#host', { basePath: '/DocImage.axd', licenseUrl: '/pricing' });// 仅视觉显示,无切换:提供一个不含数字签名的简单印章。
Doconut.signer('#host', {
basePath: '/DocImage.axd',
signatureMode: 'visual',
showSignatureModeToggle: false
});回调
| 回调 | 触发时机 | 负载 |
|---|---|---|
onReady | 在挂载时触发一次(在 reset() 时不再触发) | — |
onSourceLoaded | 文件打开并显示预览时 | { file: { token, name, pages, ext } } |
onSigned | 签名成功时 | { downloadToken, downloadName, watermarked } |
onDownload | 每次点击下载时 | { downloadName, downloadToken } |
onError | 打开、签名或下载步骤失败,或 Image 模式文件过大时 | { message } |
抛出异常的回调会被捕获并记录;它永远不会中断小部件的流程。
命令式句柄
| 方法 | 行为 |
|---|---|
reset() | 返回到投放屏幕并清除当前流程。不会再次触发 onReady。在 destroy() 之后为无操作 |
loadFile(file) | 使用 File 启动流程。除非小部件位于投放屏幕,否则为无操作;如有需要,请先调用 reset() |
destroy() | 移除监听器,清空挂载点,并冻结实例 |
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 覆盖任意子集,其余保持英文。运行时会改变的片段使用 {placeholders},例如 uploading: 'Uploading {name}…' 和 pages: '{n} pages'。
| 键 | 英文默认 |
|---|---|
dropPrompt | Drag & drop a PDF or Word file here |
dropHint | PDF or Word (.docx) |
chooseFile | Choose file |
signatureHeading | Your signature |
modeDraw / modeType / modeImage | Draw / Type / Image |
metaSummary | Signature details (optional) |
metaSignerName / metaReason / metaLocation | Signer name / Reason / Location |
signatureType | Signature type |
modeCertified / modeVisual | Digital signature / Visual only |
modeVisualNote | No certificate — a visible mark only, not cryptographically verifiable. |
outputFormat | Output format |
outputPdf / outputWord | PDF / Word (.docx) |
signAction | Sign document |
download | Download |
demoNotice | Demo — signed with the Doconut demo certificate; output is watermarked. |
signingNotEnabled | Signing is not enabled on this server. |
page / pages | 1 page / {n} pages |
更多键覆盖放置步骤、错误屏幕、演示通知的链接表单(demoNoticePrefix、demoNoticeLink、demoNoticeSuffix)以及 aria-live 公告。
当 open 或 run 回答 404 且没有 JSON 错误时,部件会显示 signingNotEnabled。来自服务器的 JSON 错误始终占优,因此诸如上传过期之类的消息会保持可见。
主题定制
部件会向其挂载元素添加 dsw 类,并从 CSS 自定义属性读取颜色、圆角和字体,这样您可以在不触及内部实现的情况下进行主题定制:
#host.dsw {
--dsw-accent: #b0522b; /* 链接, 焦点, 活动模式 */
--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; /* Type 模式 */
}默认值:--dsw-accent: #2b6cb0、--dsw-bg: #ffffff、--dsw-fg: #1a202c、--dsw-muted: #718096、--dsw-border: #cbd5e0、--dsw-radius: 8px、系统 UI 字体以及手写签名字体。
构建您自己的前端
部件是位于 DocImage.axd 上的此 HTTP 合约的客户端。路由在调用 AddSignerWidget() 之前会返回 404。错误携带 JSON 正文,{ "error": "..." },除非表格中标注为“仅状态”。未知的 ?sign= 值会返回 400。
| 路由 | 用途 | 成功响应 |
|---|---|---|
POST /DocImage.axd?sign=open (multipart, one file) | 上传 PDF 或 .docx 并打开预览 | 200 — { token, name, pages, ext } |
POST /DocImage.axd?sign=run (JSON body) | 对已上传的文件进行签名 | 200 — { downloadToken, downloadName, watermarked } |
GET /DocImage.axd?sign=download&token=<downloadToken> | 流式传输已签名的文件 | 200 — 文件,Content-Disposition: attachment,Cache-Control: no-store |
ext 在 open 响应中包含前导点(".docx")。页面预览使用标准查看器图片路由,/DocImage.axd?token={token}&page={n}&thumb=1&width={px};显示的页面变为 placement.page。
run 正文:
{
"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"
}| 字段 | 备注 |
|---|---|
token | 来自 open 的令牌 |
signature.kind | Drawn、Typed 或 Image(不区分大小写);其他任何值将变为 Drawn。仅作提示:负载始终为 PNG |
signature.payload | 纯粹的 base64 PNG,且没有 data: 前缀。它必须是真正的 PNG,解码后大小不超过 MaxSignatureImageKb |
placement.page | 从 1 开始 |
placement.x / y / w / h | 从左上角归一化 0..1,并带有 x + w ≤ 1 和 y + h ≤ 1 |
meta.signerName / reason / location | 可选。每个字段会被修剪,空值会被丢弃,并且每个字段截断为 256 个字符 |
wordOutput | pdf(默认)或 docx;对 PDF 源忽略。其他任何值将变为 pdf |
mode | certified(默认)或 visual。其他任何值将变为 certified |
downloadName 紧随输出:<source>-signed.pdf 或 <source>-signed.docx,并且 download 发送匹配的 Content-Type。
已上传的源文件和已签名的结果各自保留 30 分钟。之后,run 和 download 返回 404,并且必须再次打开文件。所有令牌均为 GUID。
| 路由 | 状态 | 何时 | 正文 |
|---|---|---|---|
| 任意 | 404 | 部件未启用 | 仅状态 |
| 任意 | 405 | 错误的动词(open 和 run 需要 POST,download 需要 GET) | 仅状态 |
open | 400 | 不是 multipart 上传 | Expected a multipart file upload. |
open | 400 | 没有文件,或文件为空 | No file uploaded. |
open | 400 | 除 .pdf 或 .docx 之外的任何内容 | Signing supports PDF and Word (.docx) files only. |
open | 413 | 上传超过 MaxUploadMb(但未超过 IIS 限制) | File is too large. |
run | 400 | 正文不是有效的 JSON,或为空 | Malformed request. / Empty request. |
run | 400 | 缺少令牌或令牌不是 GUID | Invalid token. |
run | 404 | 上传已过期或从未打开 | Upload expired — please re-open the file. |
run | 400 | 没有签名,或没有放置 | No signature supplied. / No placement supplied. |
run | 400 | 负载不是 base64、为空、太大,或不是 PNG | Signature image is not valid base64. / Signature image is empty. / Signature image is too large. / The signature image must be a PNG. |
run | 400 | 放置位置超出页面范围 | The signature or its placement is invalid. |
run | 400 | 认证模式、付费许可证且没有证书 | No signing certificate configured. |
run | 400 | 认证模式下证书已超出有效期 | The signing certificate expired on yyyy-MM-dd. / The signing certificate is not valid before yyyy-MM-dd. |
open, run | 500 | 处理失败 | 已清理的消息 |
download | 400 | 缺少令牌或令牌不是 GUID | 仅状态 |
download | 404 | 未知或已过期的令牌 | 仅状态 |
使用 fetch 的完整往返过程:
// file: 待签名的 File;pngBase64: 作为裸 base64 PNG 的签名,不含 data: 前缀,
// 例如 canvas.toDataURL('image/png').split(',')[1].
async function signFile(file, pngBase64) {
const base = '/DocImage.axd';
// 1. open: 上传文件
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: 对其签名
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: 获取已签名的文件
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);
}端点是 same-origin:此版本不支持 CORS。请将您的 UI 和小部件脚本与应用程序部署在同一来源,或在您的 UI 所在的来源下对 DocImage.axd 和 /doconut-res 进行反向代理。
在生产环境中
-
安装插件 于核心包旁边,使用相同版本:
Install-Package Doconut.NETFramework.Signer。 -
添加许可证文件。 将
Doconut.Viewer.Signer.lic放在与Doconut.Viewer.lic相同的文件夹中。 -
获取您的证书为 PFX,其中包含私钥和颁发者链,可从证书颁发机构或贵组织的内部 PKI 获取。要先进行测试,可使用演示许可证(内置的演示证书,带水印)或自签名 PFX。
-
从配置中读取证书,这样更改证书时无需修改代码:
xml<appSettings> <add key="DoconutSigner:PfxPath" value="~/App_Data/your-certificate.pfx" /> </appSettings>csharpvar 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"] ?? "", }); });将
.pfx保存在App_Data中,IIS 永不提供该文件,并且将密码从明文Web.config中移除:使用加密的配置节,或使用部署读取的密钥存储。 -
在 Certified 模式下签署测试文档。 已过期或尚未生效的证书会被
The signing certificate expired on yyyy-MM-dd.(或is not valid before)拒绝,PDF 阅读器会显示其是否信任该签名。
PDF 阅读器中的信任。 当阅读器信任证书根时,会将签名显示为有效。使用贵组织的 PKI 时,只要机器信任您的根证书(通常是组织内部的所有机器),签名即被认可。我们所知,Adobe 在任何机器上信任的证书(Adobe Approved Trust List)都是使用硬件令牌或 HSM 中的私钥颁发的,而此插件只能使用 PFX 进行签名,无法使用这些硬件。请在依赖此类信任之前与您的证书提供商确认。
Web 农场
小部件将在提供 open 的服务器内存中保存每次上传及其结果。若负载均衡器未启用粘性会话,后续的 run、download 或预览请求可能会到达另一台服务器,从而找不到该上传。通过 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.Signer.SignerPlugin>();
options.AddSignerWidget();
},
services => services.AddDoconutDistributedWidgets(store =>
{
store.RootPath = @"\\fileshare\doconut"; // 每个服务器都可以读写的文件夹
store.FarmKey = farmKey; // 至少 32 字节,在每个服务器上保持一致
// store.Ttl = TimeSpan.FromMinutes(30); // 上传保持多长时间(默认)
}));- 单个服务器无需任何操作:如果不调用此方法,将使用内存存储。
- 上传和结果在共享存储上以静止状态加密(AES-256,encrypt-then-MAC),每个文件绑定到其令牌,因而任何令牌都无法读取其他令牌的文件。
FarmKey必须至少为 32 字节,并且在每台服务器上保持一致。请从密钥存储加载;切勿硬编码。若缺少RootPath或FarmKey短于 32 字节,注册会抛出ArgumentException。- 将
RootPath指向分布式查看器使用的相同共享位置,并为每台服务器提供相同的签名证书。
API 参考
Facade 和 widget 选项位于 Doconut 命名空间;请求和结果类型位于 Doconut.Core.Models.Signing。SignerPlugin 位于 Doconut.Plugins.Signer。
DocumentSigner
public sealed class DocumentSigner
{
public Task<SignResult> SignAsync(
Stream source, string sourceExtension, SignRequest request,
SigningCertificate? cert = null, CancellationToken ct = default);
}从 DoconutHost.Services 解析得到;构造函数是 internal。sourceExtension 是 ".pdf" 或 ".docx"。在付费许可证下,cert 被使用,输出为干净;在临时许可证下,使用内置演示证书,cert 被忽略,输出带有水印。
SignRequest
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
}一次放置的可见签名,加上可选的签署者元数据。
VisibleSignature and SignatureKind
public sealed record VisibleSignature(SignatureKind Kind, byte[] PngBytes)
{
public bool IsValid { get; } // PngBytes 不能为空
}
public enum SignatureKind { Drawn, Typed, Image }PngBytes 是每种类型的 PNG。手绘或键入的签名是透明的;上传的图像保留其透明度,因此不透明的 JPG 仍保持不透明。Kind 仅作为提示。
SignaturePlacement
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 是从 1 开始的;X、Y、W 和 H 是相对于左上角归一化的 0..1。
SignatureMode and WordOutput
public enum SignatureMode { Certified, Visual } // Certified 是默认
public enum WordOutput { Pdf, Docx } // Pdf 是默认; 忽略 PDF 源SignResult
public sealed record SignResult(Stream Stream, string Extension);已签名的文档作为可寻址流,以及其带点的扩展名(".pdf" 或 ".docx")。
SigningCertificate
public sealed class SigningCertificate
{
public byte[]? PfxBytes { get; init; }
public string? PfxPath { get; init; }
public string Password { get; init; } = "";
public bool HasMaterial { get; } // PfxBytes 不能为空,或 PfxPath 不能为空
}设置 PfxBytes 或 PfxPath,以及 Password。这些 setter 为 init-only:项目需要 C# 9.0 或更高版本。
SignerWidgetOptions
public sealed class SignerWidgetOptions
{
public int MaxUploadMb { get; set; } = 25;
public int MaxSignatureImageKb { get; set; } = 512;
public SigningCertificate? SigningCertificate { get; set; }
}通过 DoconutOptions.AddSignerWidget(Action<SignerWidgetOptions>? configure = null) 设置,它返回 DoconutOptions,因此可以链式调用。null SigningCertificate 表示在临时许可证下使用演示证书,且仅在付费许可证下支持 Visual 签名。
故障排除
| 症状 | 原因 | 解决方案 |
|---|---|---|
在添加插件后,每个请求返回空的 500;事件日志显示 The Signer plugin is registered via AddPlugin but no active license grants Signer. | 没有许可证、TRIAL 文件、许可证缺少 Signer,或付费许可证超出其版本窗口 | 安装授予 Signer 的许可证,或移除 AddPlugin<SignerPlugin>() |
事件日志显示 AddSignerWidget() was called but the Signer plugin is not registered. | 小部件已启用但未加载其插件 | 添加 options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>() |
事件日志显示 Doconut Signer: the certificate file was not found at '{path}'. | PfxPath 指向缺失的文件 | 修正路径;将文件部署到应用池账户可读取的位置 |
事件日志显示 Doconut Signer: the signing certificate could not be opened — the password is incorrect or the file is not a valid .pfx. | 密码错误,或不是 PKCS#12 文件 | 检查密码;使用真实的 .pfx |
事件日志显示 Doconut Signer: the signing certificate has no private key. Re-export the .pfx INCLUDING the private key. | PFX 导出时未包含私钥 | 重新导出并包含私钥 |
new SigningCertificate { … } 无法编译 | 项目使用 C# 7.3,无法设置 init-only 属性 | 将 <LangVersion> 设置为 9.0 或更高版本 |
解析 DocumentSigner 时抛出 No IDocumentSigner is registered. | SignerPlugin 未注册 | 在 DoconutHost.Initialize 中添加 AddPlugin<SignerPlugin>() |
| 输出带有水印 | 许可证为临时(演示/NFR) | 使用授予 Signer 的付费许可证 |
run 返回 400 No signing certificate configured. | 使用付费许可证、Certified 模式且没有证书 | 配置 SigningCertificate,或在 Visual 模式下签名 |
run 返回 400 The signing certificate expired on yyyy-MM-dd. | 证书已过期 | 更换证书;期间 Visual 签名仍可使用 |
小部件加载但显示 Signing is not enabled on this server. | AddSignerWidget() 未被调用,或 basePath 不是 '/DocImage.axd' | 调用 AddSignerWidget();设置 basePath: '/DocImage.axd' |
| 大文件上传时显示 IIS 错误页,而不是小部件的消息 | maxRequestLength / maxAllowedContentLength 低于 MaxUploadMb | 将两个主机限制提升至超过 MaxUploadMb |
run 返回 400 The signature image must be a PNG.、Signature image is not valid base64. 或 Signature image is too large. | 自定义 UI 发送了 data: URL、JPG,或超过 MaxSignatureImageKb | 在限制内发送裸的 base64 PNG |
open 返回 413 File is too large. | 上传超过 MaxUploadMb | 在 AddSignerWidget 中提升 MaxUploadMb;小部件的 maxUploadMb 仅是客户端检查 |
run 或 download 返回 404 Upload expired — please re-open the file. | 30 分钟窗口已过,或集群中的另一台服务器没有该上传文件 | 重新打开文件;在集群中,注册 AddDoconutDistributedWidgets |
已签名的 .docx 在某些查看器中不显示签名 | Word 输出包含 OOXML 包签名,许多查看器不显示 | 签名为 PDF(默认) |
| PDF 阅读器显示签名者身份未知 | 阅读器不信任证书根(演示证书永不被信任) | 使用受阅读器信任的根证书 |
| 当 UI 位于其他来源时小部件失败 | 端点未提供 CORS 支持 | 在相同来源提供 UI,或对 DocImage.axd 和 /doconut-res 进行反向代理 |
| 主题未生效 | 选择器针对挂载内部的元素 | 直接定位挂载本身:#host.dsw 或 #host |
框架说明
与 ASP.NET Core 包相比,此包仅在托管方面有所不同;API、端点契约、部件脚本和许可规则保持一致。
- 注册 位于
Application_Start,通过DoconutHost.Initialize,而不是builder.Services.AddDoconut。诸如AddDoconutDistributedWidgets的服务放在其第二个参数中。 - 端点 由
DocImage.axd提供服务,脚本由DoconutResourceModule提供,二者均在Web.config中注册,而不是UseDoconut()和UseDoconutResources()。部件需要basePath: '/DocImage.axd'。 - 启动失败 在每个请求中表现为一个空的
500,原因记录在 Windows 事件日志中。 - 上传 在 Doconut 看到之前,ASP.NET 会完整读取上传内容,因此 IIS 限制必须高于
MaxUploadMb。 - 没有启动日志行 关于证书:三个证书错误仍会抛出,但标识证书的日志行未被写入。
- C# 9.0 或更高版本 需要来设置
SigningCertificate的 init-only 属性。 - 仅限 Windows,如同 .NET Framework 包的其余部分。
此页面对您有帮助吗?