【发布时间】:2015-01-27 02:37:12
【问题描述】:
我想重新编写将 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: Cannot access a closed 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();
它会创建一个空文档。我做错了什么?
【问题讨论】:
-
看看this answer。
-
签名的安全性不是我的责任。我的唯一职责是将签名应用于 MemoryStream 而不是 FileStream。我确实在
st.Close();之前放了st.Writer.CloseStream = false;,谁能帮我签署一个MemoryStream,好吗?
标签: c# pdf itext memorystream pdfstamper