在使用iTextSharp 5.3.4.0时,我在使用PdfStamper和MemoryStream时遇到了困难。
MemoryStream始终为空。
PdfReader pdfReader = new PdfReader(Server.MapPath(@"Document.pdf"));
MemoryStream memoryStream = new MemoryStream();
PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, memoryStream, '\0');
//...
pdfStamper.Writer.CloseStream = false;
pdfStamper.Close();
byte[] bt = memoryStream.GetBuffer(); //.ToArray()
pdfReader.Close();Download Project (full source code)
我该如何解决这个问题?谢谢!
发布于 2013-07-18 15:05:16
在Default.aspx.cs中,您可以做一些问题的代码块中遗漏的相关操作:
PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, memoryStream, '\0');
PdfSignatureAppearance pdfSignatureAppearance = pdfStamper.SignatureAppearance;
//...
pdfSignatureAppearance.PreClose(exc);
//...
pdfStamper.Writer.CloseStream = false;
pdfStamper.Close();无论何时调用PdfSignatureAppearance.PreClose,,都必须使用PdfSignatureAppearance.Close,,而不是PdfStamper.Close, cf。方法文档:
/**
* This is the first method to be called when using external signatures. The general sequence is:
* preClose(), getDocumentBytes() and close().
* <p>
* If calling preClose() <B>dont't</B> call PdfStamper.close().
* <p>
* <CODE>exclusionSizes</CODE> must contain at least
* the <CODE>PdfName.CONTENTS</CODE> key with the size that it will take in the
* document. Note that due to the hex string coding this size should be
* byte_size*2+2.
* @param exclusionSizes a <CODE>HashMap</CODE> with names and sizes to be excluded in the signature
* calculation. The key is a <CODE>PdfName</CODE> and the value an
* <CODE>Integer</CODE>. At least the <CODE>PdfName.CONTENTS</CODE> must be present
* @throws IOException on error
* @throws DocumentException on error
*/
public void PreClose(Dictionary<PdfName, int> exclusionSizes) {(来自)
/**
* Closes the document. No more content can be written after the
* document is closed.
* <p>
* If closing a signed document with an external signature the closing must be done
* in the <CODE>PdfSignatureAppearance</CODE> instance.
* @throws DocumentException on error
* @throws IOException on error
*/
public void Close() {(来自)
原因是,当您使用CreateSignature(pdfReader, memoryStream, '\0'),创建PdfStamper时,stamper本身并不写入内存流,而是写入内部ByteBuffer (这对于最终的签名创建和集成是必需的)。在PdfSignatureAppearance.Close期间,该ByteBuffer的内容被写入内存流。
而且我看到你在用
byte[] bt = memoryStream.GetBuffer();请不要这样!除非您确定您正确地解释了缓冲区内容(可能包含其他垃圾数据),否则请使用
byte[] bt = memoryStream.ToArray();而不是。
https://stackoverflow.com/questions/17711070
复制相似问题