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

时间:2016-07-18 07:33:32

标签: c# pdf itext digital-signature

是否可以使用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);
}

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

1 个答案:

答案 0 :(得分:1)

我回答我自己的问题......如果它对别人有用我就这样做了。 我发现了一个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);
}