我正在使用 iTextSharp 处理 PDF。我想将签名图像添加到签名字段而不对文档进行数字签名(不涉及证书)。
这可能吗?我可以使用数字签名,但我也想在签名字段上添加签名图像而不使用任何证书。
更新:
现在写我有以下代码。
// Set PDF Reader and PDF Stamper
PdfReader reader = new PdfReader(sourceDocument);
// File stream where PDF will write
FileStream fout = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite);
PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', null, true);
// Set PDF Appearance
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
iTextSharp.text.Image signatureFieldImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
appearance.SignatureGraphic = signatureFieldImage;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC;
appearance.SetVisibleSignature(signatureFieldName);
stamper.Close();
reader.Close();
fout.Close();
但是当我尝试运行它时,它给出了以下错误:
Signature defined. Must be closed in PdfSignatureAppearance
最佳答案
您正在使用代码对您不想进行数字签名的 PDF 进行数字签名 ;-)
如果文档已经签名,添加任何额外内容(例如图像)将破坏签名,但如果文档尚未签名,您有不同的选择。
您需要使用 PdfStamper
正常方式,即:不是通过使用 CreateSignature()
方法,而是按照描述的方式在 chapter 6我关于 iText 的书。您还需要决定是否重要的是(1) 图像是签名字段的一部分(在这种情况下,它会在 PDF 实际签名时消失)或 (2) 图片需要作为内容流的一部分添加(在这种情况下,一旦您签署文档,图片仍会存在)。
如果是(1),请查看my book about digital signatures 的代码示例2.6 和代码示例2.7。 (有关代码的 C# 版本,请参阅 CreateEmptyField 示例)。在代码示例 2.6 中,您将了解如何创建具有自定义 PdfAppearance
的 PdfFormField
。在代码示例 2.7 中,您将了解如何使用 PdfStamper
向现有文档添加签名字段。在您的情况下,您将删除现有的签名字段(使用 removeField()
方法)并将其替换为新的 PdfFormField
在完全相同的坐标处具有不同的外观.
在 (2) 的情况下,您只需创建一个 Image
对象并将其添加到从 检索的
使用 PdfContentByte
>PdfStamperGetOverContent()
方法。查看examples of chapter 6寻找灵感。
在这两种情况下,您都需要知道这两种情况下的坐标和页码。可以像这样检索此信息:
AcroFields form = stamper.AcroFields;
AcroFields.FieldPosition f = form.GetFieldPositions("mySigName")[0];
您将获得这样的页面:f.page
和定义如下位置的 Rectangle
:f.position
。
由于我们不确切知道您需要哪种类型的最终结果,因此很难提供更多细节。您的代码中最重要的错误是您使用 CreateSignature()
方法获取 PdfStamper
对象,而您不想签署文档。
关于c# - 在 PDF 上添加签名图像而不使用 iTextSharp 对其进行数字签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20660839/