iTextSharp 提取签名图像
原文
本文使用 iTextSharp 5.5.13.2,记录使用 iTextSharp 提取图片时,获得的知识点。
pdf 中的签名并不是单纯的一张图片,它是由一张基础的底色图和一张蒙版图片组成。需要提取底图和Mask。
下面是提取签名的底图和Mask的方法
public class ExtImageRenderListener : IRenderListener
{
public List<System.Drawing.Image> Images = new List<System.Drawing.Image>();
public List<System.Drawing.Image> Masks = new List<System.Drawing.Image>();
public void BeginTextBlock()
{ }
public void EndTextBlock()
{ }
public void RenderText(TextRenderInfo renderInfo)
{ }
public void RenderImage(ImageRenderInfo renderInfo)
{
PdfImageObject imageObject = renderInfo.GetImage();
if (imageObject == null)
{
Console.WriteLine("Image {0} could not be read.", renderInfo.GetRef().Number);
}
else
{
Images.Add(imageObject.GetDrawingImage());
PRStream maskStream = (PRStream)imageObject.GetDictionary().GetAsStream(PdfName.SMASK);
if (maskStream != null)
{
PdfImageObject maskImageObject = new PdfImageObject(maskStream);
Masks.Add(maskImageObject.GetDrawingImage());
}
else
{
Masks.Add(null);
}
}
}
}
String source = @"E:\1.pdf";
int count = 0;
using (PdfReader sourceReader = new PdfReader(source))
{
AcroFields acroFields = sourceReader.AcroFields;
foreach (string name in acroFields.GetSignatureNames())
{
PdfStream xObject = (PdfStream)PdfReader.GetPdfObjectRelease(sourceReader.AcroFields.GetNormalAppearance(name));
PdfDictionary resources = xObject.GetAsDict(PdfName.RESOURCES);
ExtImageRenderListener strategy = new ExtImageRenderListener();
PdfContentStreamProcessor processor = new PdfContentStreamProcessor(strategy);
processor.ProcessContent(ContentByteUtils.GetContentBytesFromContentObject(xObject), resources);
System.Drawing.Image drawingImage = strategy.Images[0];
System.Drawing.Image drawingMask = strategy.Masks[0];
if (drawingImage != null)
{
drawingImage.Save(count++ + @".png");
}
if (drawingMask != null)
{
drawingMask.Save(count++ + @"Mask.png");
}
}
}