签名插件
使用可见签名和数字封印对 PDF 和 Word 文档进行签名
Signer 插件在文档上放置可见签名,并默认使用 PDF 阅读器可以验证的数字签名对其进行封印。它可以签署 PDF 和 Word (.docx) 文件。可见签名始终是 PNG 图像:由签署者绘制、键入或上传。
| 使用场景 | 适用情况 |
|---|---|
DocumentSigner (C#) | 您在服务器上签署,无需浏览器参与 |
Drop-in widget (doconutSigner.js) | 您想在页面中拥有现成的上传、签署和下载界面 |
HTTP endpoints (?sign=open|run|download) | 您想基于文档化的服务器合同自行构建签署 UI |
每个签名仅放置一次,位于单页。签署者的姓名、原因和位置可以随签名一起携带。
安装包
安装最新稳定的 Signer 插件:
dotnet add package Doconut.NET8.Signer要将插件固定到本文档描述的发布版本,请单独传递版本号:
dotnet add package Doconut.NET8.Signer --version 26.10.0保持 Signer 包的版本与 Doconut.NET8 相同。包 ID 为 Doconut.NET8.Signer;.<version> 仅出现在下载的 .nupkg 文件名中。
插件的许可证文件 Doconut.Viewer.Signer.lic 放在与 Doconut.Viewer.lic 相同的文件夹中;它会与查看器许可证一起读取。
平台。 插件可在 Doconut.NET8 所在的任何环境运行:Windows,以及基于 glibc 的 x64 Linux(不包括 Alpine 或其他基于 musl 的发行版)。在 Linux 上,在打开第一个文档之前请安装字体配置库:
apt-get update && apt-get install -y libfontconfig1在 RHEL、Fedora 及类似发行版上,包为 fontconfig。如果缺少它,打开文档会因 The system library libfontconfig1 is missing. Install it (Debian/Ubuntu: apt-get install -y libfontconfig1) and see the Linux section of the Doconut documentation. 而失败。
注册插件
像所有 Doconut 插件一样,Signer 在 AddDoconut() 中使用 AddPlugin<TPlugin>() 注册:
builder.Services.AddDoconut(options =>
{
options.LicensePath = "Doconut.Viewer.lic";
options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>();
});这就是 C# 外观层所需的全部。小部件及其 HTTP 端点是单独的可选项,AddSignerWidget()(参见 内嵌小部件)。
插件需要一个授予 Signer 功能的许可证。若没有许可证,AddDoconut() 会在启动时抛出异常,在应用响应请求之前:
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.它会因缺少许可证、旧版 TRIAL 文件、缺少 Signer 的许可证,以及在版本窗口之外使用的付费许可证而抛出异常。临时 Demo/NFR 许可证也被接受。参见 许可证设置 了解许可证的加载方式。
许可与水印
| 许可证状态 | 启动 | 认证签名 | 可视签名 |
|---|---|---|---|
付费许可证授予 Signer,已配置证书 | 启动 | 使用您的证书封印,干净(watermarked: false) | 干净 |
付费许可证授予 Signer,无证书 | 启动 | 拒绝:No signing certificate configured. | 干净 |
| 付费许可证,证书已过期或尚未生效 | 启动(启用小部件时记录警告) | 拒绝:The signing certificate expired on yyyy-MM-dd. | 干净 |
| 临时 Demo/NFR 许可证,已激活或已过期 | 启动 | 使用内置演示证书封印,带水印(watermarked: true) | 带水印 |
无许可证、旧版 TRIAL 文件、缺少 Signer 的许可证,或在版本窗口之外的付费许可证 | AddDoconut() 抛出异常 | — | — |
对于 C# 外观层和小部件,规则相同:当许可证不是付费查看器许可证或为临时许可证时,输出会带水印。在临时许可证下,插件始终使用其内置的演示证书进行签名,您配置的任何证书都不会被使用。
演示证书会生成真实的封印,但 PDF 阅读器不信任它。可以在评估许可证上构建并端到端测试集成;若要获得干净、可信的输出,您需要付费许可证以及您自己的 签名证书。
从 C# 使用
DocumentSigner 由 AddDoconut() 注册,并通过依赖注入解析。它的构造函数是 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(visible signature + digital seal);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, ct);
return output.ToArray();
}
}
}SignAsync 接受源流、其扩展名(".pdf" 或 ".docx")、请求以及证书 用于此调用。Facade 不会读取 SignerWidgetOptions.SigningCertificate;该设置用于小部件。使用演示许可证或在 Visual 模式下传递 null。
SignResult 将已签名的文档保存为可定位的流,并附带其 Extension(".pdf" 或 ".docx"),以便您可以为文件命名。您拥有该流:使用完毕后请释放它。
Visual 签名仅在图像上盖章,且不需要证书:
var signer = app.Services.GetRequiredService<DocumentSigner>();
byte[] signaturePng = File.ReadAllBytes("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(stream, ".pdf", request, ct: ct);除非您要求 Word 输出,否则 Word 源会签署为 PDF。使用 result.Extension 命名结果:
var signer = app.Services.GetRequiredService<DocumentSigner>();
byte[] signaturePng = File.ReadAllBytes("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。提供字节数组或文件路径以及密码:
builder.Services.AddDoconut(options =>
{
options.LicensePath = "Doconut.Viewer.lic";
options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>();
options.AddSignerWidget(widget =>
{
widget.SigningCertificate = new SigningCertificate
{
PfxBytes = File.ReadAllBytes("/secure/signing.pfx"),
Password = builder.Configuration["Signing:PfxPassword"],
};
});
});builder.Services.AddDoconut(options =>
{
options.LicensePath = "Doconut.Viewer.lic";
options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>();
options.AddSignerWidget(widget =>
{
widget.SigningCertificate = new SigningCertificate
{
PfxPath = "/secure/signing.pfx",
Password = builder.Configuration["Signing:PfxPassword"],
};
});
});证书仅保存在内存中。它永不被记录、返回给客户端或持久化,密码也永不出现在日志行或错误信息中。
要求:
- 一个 PFX / PKCS#12 捆绑包 包含私钥。仅有公钥的文件(
.cer、.crt)无法签名。请一起导出发行者链,以便 PDF 封签能够携带它。 - 正确的密码。
- 位于其 有效期窗口 内。过期或尚未生效的证书不会阻止应用启动:启动时会记录为 Warning,且在证书被替换之前,已认证的签名会被拒绝。可视签名不受影响。
- 用于文档签名:密钥用法需包含 digital signature 或 non-repudiation,若存在扩展密钥用法,则必须允许文档签名、电子邮件保护或客户端身份验证。若证书用于其他用途(例如 TLS 服务器证书),仍可签名,但会记录为 Warning,且 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),并设置密码。
启动检查
启用小部件后,SignerWidgetOptions.SigningCertificate 中的证书会在 AddDoconut() 内检查一次,从而在启动时而非首次签名时捕获错误配置的 PFX。三类问题会抛出 InvalidOperationException:
| 信息 | 修复 |
|---|---|
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 |
否则主机在启动时只会写入一行日志。证书准备就绪时的日志信息:
Doconut Signer: using certificate '{subject}' (valid until yyyy-MM-dd). Signatures are digitally sealed.证书过期、尚未生效或未用于文档签名时的 Warning:
Doconut Signer: the signing certificate '{subject}' expired on yyyy-MM-dd. Certified signatures will be refused until it is replaced.
Doconut Signer: the signing certificate '{subject}' is not valid before yyyy-MM-dd. Certified signatures will be refused until then.
Doconut Signer: the signing certificate '{subject}' is not issued for document signing (its key usage excludes it). PDF readers will flag these signatures.以及未配置证书时的 Information:
Doconut Signer: no signing certificate configured — output uses the built-in demo certificate and is watermarked. Set SignerWidgetOptions.SigningCertificate to sign with your own certificate.最后一行在所有许可证下都相同。付费许可证下演示证书永不使用:没有证书时,仅可使用可视签名。
C# 外观层不会在启动时检查。您传递给 SignAsync 的证书会在签名时读取,因此错误的路径或密码会导致该调用失败。
即插即用小部件
启用端点
小部件的 ?sign=open|run|download 端点默认 关闭。在插件注册旁边启用它们:
builder.Services.AddDoconut(options =>
{
options.LicensePath = "Doconut.Viewer.lic";
options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>();
options.AddSignerWidget(widget =>
{
widget.MaxUploadMb = 25; // 默认
widget.MaxSignatureImageKb = 512; // 默认
// widget.SigningCertificate: 参见 Certificate 设置; 将其保留为 null 以进行演示(带水印)签名
});
});AddSignerWidget() 在没有参数的情况下使用默认设置启用小部件。它本身并不授予签名权限:它需要 AddPlugin<SignerPlugin>(),否则 AddDoconut() 会抛出:
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.如果没有 AddSignerWidget(),每个 ?sign= 请求都会返回 404。脚本本身仍然会被提供,因此小部件会加载并绘制其投放区,然后在第一次请求时报告 Signing is not enabled on this server.。
嵌入它
UseDoconutResources() 在 {ResourcesPath}/js/doconutSigner.js 提供脚本(默认 /doconut-res/js/doconutSigner.js)。这是一个单一的、独立的文件,没有任何依赖:
<div id="host"></div>
<script src="/doconut-res/js/doconutSigner.js"></script>
<script>
const handle = Doconut.signer('#host', { basePath: '/doconut' });
</script>Doconut.signer(selectorOrElement, options) 接受 CSS 选择器或元素,如果未找到挂载点则抛出错误,并返回一个句柄。
签署者上传 PDF 或 .docx 文件,创建签名(在画布上 绘制、在签名字体中 输入 名称,或从 PNG、JPG 或 GIF 图片),将其拖动并调整大小放置在页面上,然后签署并下载结果。小部件始终以 PNG 形式发送签名;上传的图片会在浏览器中转换为符合 520×160 的 PNG。
选项
| 选项 | 类型 | 默认值 | 备注 |
|---|---|---|---|
basePath | string | '/doconut' | 提供 ?sign= 端点和预览图像的地点 |
resPath | string | '/doconut-res' | 保留;小部件自带 CSS |
maxUploadMb | number | 25 | 仅客户端检查,因此超大文件会快速失败。服务器上限为 MaxUploadMb,位于 AddSignerWidget |
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: '/doconut', licenseUrl: '/pricing' });// 仅视觉显示,无切换开关:提供一个不含数字签名的简单印章。
Doconut.signer('#host', {
basePath: '/doconut',
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: '/doconut',
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 字体,以及手写签名字体。
构建您自己的前端
该小部件是此 HTTP 合约的客户端。所有三个路由都位于 UseDoconut() 挂载的路径下(通常为 /doconut),并在调用 AddSignerWidget() 之前响应 404。错误会携带 JSON 正文,{ "error": "..." },除非表格中标注为“仅状态”。未知的 ?sign= 值会返回 400。
| 路由 | 用途 | 成功响应 |
|---|---|---|
POST ?sign=open(multipart,单文件) | 上传 PDF 或 .docx 并打开预览 | 200 — { token, name, pages, ext } |
POST ?sign=run(JSON 正文) | 对已上传的文件进行签名 | 200 — { downloadToken, downloadName, watermarked } |
GET ?sign=download&token=<downloadToken> | 流式传输已签名的文件 | 200 — 文件,Content-Disposition: attachment,Cache-Control: no-store |
ext 在 open 响应中包含前导点(".docx")。页面预览使用标准查看器图片路由,{basePath}?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 | 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: 要签名的文件; pngBase64: 作为裸 base64 PNG 的签名,不带 data: 前缀,
// 例如 canvas.toDataURL('image/png').split(',')[1].
async function signFile(file, pngBase64) {
const base = '/doconut';
// 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 和小部件脚本与 Doconut 位于同一来源,或在您的 UI 来源下对两个 /doconut 路径(中间件路径和资源路径)进行反向代理。
在生产环境
-
安装插件 放在核心包旁边,使用相同的版本:
dotnet add package Doconut.NET8.Signer。 -
添加许可证文件。 将
Doconut.Viewer.Signer.lic放在与Doconut.Viewer.lic相同的文件夹中。 -
获取您的证书为 PFX,其中包含私钥和颁发者链,来自证书颁发机构或您组织自己的 PKI。要先尝试,可使用演示许可证(内置的演示证书,带水印)或自签名的 PFX。
-
从配置中读取证书,这样更改它永远不需要修改代码:
json"DoconutSigner": { "PfxPath": "certs/your-certificate.pfx" }csharpvar signerSettings = builder.Configuration.GetSection("DoconutSigner"); builder.Services.AddDoconut(options => { options.LicensePath = "Doconut.Viewer.lic"; options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>(); options.AddSignerWidget(widget => widget.SigningCertificate = new SigningCertificate { PfxPath = Path.Combine(builder.Environment.ContentRootPath, signerSettings["PfxPath"]), Password = signerSettings["Password"] ?? "", }); });将
.pfx保持在wwwroot之外,并将密码保存在appsettings.json之外:在开发中使用用户机密(dotnet user-secrets set "DoconutSigner:Password" "<password>"),在生产中使用环境变量(DoconutSigner__Password)或金库。 -
检查启动日志。 它应显示
using certificate '{subject}' (valid until …). Signatures are digitally sealed.。如果出现警告,则表示证书已过期、尚未生效,或未用于文档签名。
信任 PDF 阅读器。 当阅读器信任证书根时,会将签名显示为有效。使用您组织的 PKI 时,只要机器信任您的根证书(通常是组织内部的所有机器),签名就有效。我们所知,Adobe 在任何机器上信任的证书(Adobe Approved Trust List)是使用硬件令牌或 HSM 上的私钥颁发的,而此插件只能使用 PFX 进行签名,无法使用这些私钥。请在依赖此类信任之前与您的证书提供商确认。
Web 农场
小部件将每个上传及其结果保存在提供 open 的节点内存中。若负载均衡器未使用粘性会话,后续的 run、download 或预览请求可能会到达另一节点,从而找不到该上传。请在 AddDoconut() 之后一次性注册共享的加密小部件存储:
byte[] farmKey = Convert.FromBase64String(builder.Configuration["Doconut:FarmKey"]);
builder.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);
}通过依赖注入解析;构造函数为 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。
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 签名。
故障排除
| 症状 | 原因 | 解决方案 |
|---|---|---|
AddDoconut() 抛出 The Signer plugin is registered via AddPlugin but no active license grants Signer. | 没有许可证,TRIAL 文件,许可证缺少 Signer,或付费许可证超出其版本窗口 | 安装授予 Signer 的许可证,或移除 AddPlugin<SignerPlugin>() |
AddDoconut() 抛出 AddSignerWidget() was called but the Signer plugin is not registered. | 小部件已启用但缺少其插件 | 添加 options.AddPlugin<Doconut.Plugins.Signer.SignerPlugin>() |
AddDoconut() 抛出 Doconut Signer: the certificate file was not found at '{path}'. | PfxPath 指向了一个缺失的文件 | 修复路径;将文件部署到应用账户可读取的位置 |
AddDoconut() 抛出 Doconut Signer: the signing certificate could not be opened — the password is incorrect or the file is not a valid .pfx. | 密码错误,或不是 PKCS#12 文件 | 检查密码;使用真实的 .pfx |
AddDoconut() 抛出 Doconut Signer: the signing certificate has no private key. Re-export the .pfx INCLUDING the private key. | PFX 导出时未包含私钥 | 重新导出并包含私钥 |
解析 DocumentSigner 抛出 No IDocumentSigner is registered. | SignerPlugin 未注册 | 在 AddDoconut() 中添加 AddPlugin<SignerPlugin>() |
| 输出带有水印 | 许可证为临时(Demo/NFR) | 使用授予 Signer 的付费许可证 |
run 返回 400 No signing certificate configured. | 使用付费许可证、Certified 模式且未配置证书 | 配置 SigningCertificate,或在 Visual 模式下签名 |
run 返回 400 The signing certificate expired on yyyy-MM-dd. | 证书已过期 | 更换证书;期间 Visual 签名仍可工作 |
| 日志显示输出“使用内置演示证书”,但付费许可证拒绝 Certified 签名 | 无论许可证如何,只要未配置证书都会写入该行 | 配置 SigningCertificate |
小部件加载但显示 Signing is not enabled on this server. | AddSignerWidget() 未被调用,或 basePath 与 UseDoconut() 挂载位置不匹配 | 调用 AddSignerWidget();修复 basePath |
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 | 在 cap 中发送纯 base64 PNG |
open 返回 413 File is too large. | 上传超过了 MaxUploadMb | 在 AddSignerWidget 中提升 MaxUploadMb;小部件的 maxUploadMb 仅为客户端检查 |
run 或 download 返回 404 Upload expired — please re-open the file. | 30 分钟窗口已过期,或 web-farm 节点没有该上传文件 | 重新打开文件;在集群中,注册 AddDoconutDistributedWidgets |
已签名的 .docx 在某些查看器中不显示签名 | Word 输出携带 OOXML 包签名,许多查看器不显示 | 签名为 PDF,默认 |
| PDF 阅读器显示签署者身份未知 | 阅读器不信任证书根(演示证书永不被信任) | 使用受阅读器信任根的证书 |
| 当 UI 位于其他来源时小部件失败 | 端点未提供 CORS 支持 | 在相同来源提供 UI,或对 Doconut 路径进行反向代理 |
| 主题未生效 | 选择器针对挂载内部的元素 | 直接定位挂载本身:#host.dsw 或 #host |
此页面对您有帮助吗?