c#itextsharp如何获取数字签名图像

本文关键字:数字签名 图像 获取 何获取 c#itextsharp | 更新日期: 2023-09-27 17:57:36

是否可以使用c#代码使用itextsharp获取pdf文件中任何数字签名的图像?

PdfReader pdf = new PdfReader("location.pdf");
AcroFields acroFields = pdf.AcroFields;
List<string> names = acroFields.GetSignatureNames();
foreach (var name in names)
{
    PdfDictionary dict = acroFields.GetSignatureDictionary(name);
}

通过这些简单的行,我可以获得签名字典,但从这个对象我无法获得图像的内容。有人能帮忙吗?

c#itextsharp如何获取数字签名图像

我回答自己的问题。。。如果它对其他人有用的话,我就这样做了。我找到了一个Java类来做我想要做的事情,并用C#翻译了它。

class XyzmoSignatureDataExtractor
{
    private PdfReader reader;
    public XyzmoSignatureDataExtractor(PdfReader reader)
    {
        this.reader = reader;
    }
    public PdfImageObject extractImage(String signatureName) 
    {
        MyImageRenderListener listener = new MyImageRenderListener();
        PdfDictionary sigFieldDic = reader.AcroFields.GetFieldItem(signatureName).GetMerged(0);
        PdfDictionary appearancesDic = sigFieldDic.GetAsDict(PdfName.AP);
        PdfStream normalAppearance = appearancesDic.GetAsStream(PdfName.N);
        PdfDictionary resourcesDic = normalAppearance.GetAsDict(PdfName.RESOURCES);
        PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
        processor.ProcessContent(ContentByteUtils.GetContentBytesFromContentObject(normalAppearance), resourcesDic);        
        return listener.image;
    }
    class MyImageRenderListener : IRenderListener
    {
        public void BeginTextBlock() { }
        public void EndTextBlock() { }
        public void RenderImage(ImageRenderInfo renderInfo)
        {
            try
            {
                image = renderInfo.GetImage();
            }
            catch (Exception e)
            {
                throw new Exception("Failure retrieving image", e);
            }
        }
        public void RenderText(TextRenderInfo renderInfo) { }
        public PdfImageObject image = null;
    }
}

要使用类并保存图像,我只喜欢这样做:

PdfReader reader = new PdfReader("location.pdf");
XyzmoSignatureDataExtractor extractor = new XyzmoSignatureDataExtractor(reader);
AcroFields acroFields = reader.AcroFields;
foreach (string name in  acroFields.GetSignatureNames())
{
  PdfImageObject image = extractor.extractImage(name);
  var _image = image.GetDrawingImage();
  string file_name = "sig." + image.GetFileType();
  _image.Save(file_name);
}