我找到了将PDF文件签名为新文件的旧代码,它将签署由Web服务发送的MemoryStreams(字节数组)。简单吧?那是昨天。今天我无法让它发挥作用。
这是旧代码,它使用FileStreams并且可以工作:
public static string OldPdfSigner(PdfReader pdfReader, string destination, string password, string reason, string location, string pathToPfx)
{
using (FileStream pfxFile = new FileStream(pathToPfx, FileMode.Open, FileAccess.Read))
{
...
using (PdfStamper st = PdfStamper.CreateSignature(pdfReader, new FileStream(destination, FileMode.Create, FileAccess.Write), '\0'))
{
PdfSignatureAppearance sap = st.SignatureAppearance;
sap.SetCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
sap.Reason = reason;
sap.Location = location;
return destination;
}
}
}
以下是我自己重做的内容,它会抛出System.ObjectDisposedException:无法访问已关闭的Stream。
public static byte[] PdfSigner(PdfReader pdfReader, string password, string reason, string location, string pathToPfx)
{
using (FileStream pfxFile = new FileStream(pathToPfx, FileMode.Open, FileAccess.Read))
{
...
MemoryStream outputStream = new MemoryStream();
using (PdfStamper st = PdfStamper.CreateSignature(pdfReader, outputStream, '\0'))
{
st.Writer.CloseStream = false;
PdfSignatureAppearance sap = st.SignatureAppearance;
sap.SetCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
sap.Reason = reason;
sap.Location = location;
st.Close();
outputStream.Position = 0;
return outputStream.ToArray();
}
}
}
如果我发表评论
st.Close();
它会创建一个空文档。我做错了什么?
答案 0 :(得分:21)
不是特定于您的签名代码,但在使用MemoryStream
和PdfStamper
时,请遵循以下一般模式:
using (MemoryStream ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(reader, ms, '\0', true)) {
// do stuff
}
return ms.ToArray();
}
MemoryStream
实施IDisposable
,因此请添加using
声明。PdfStamper
using
语句负责处理对象,因此您无需调用Close()
,也无需设置CloseStream
属性PdfStamper
using
语句中返回字节数组太快,因此您的MemoryStream
实际上是无操作。返回PdfStamper
using
语句的字符数组 , MemoryStream
using
语句。MemoryStream
Position
属性。PdfStamper
构造函数 - 它来自我填写表单的一些测试代码,并使用您需要的任何构造函数/方法进行签名。