首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PdfStamper.CreateSignature和空MemoryStream

PdfStamper.CreateSignature和空MemoryStream
EN

Stack Overflow用户
提问于 2013-07-18 06:03:52
回答 1查看 3.5K关注 0票数 1

在使用iTextSharp 5.3.4.0时,我在使用PdfStamper和MemoryStream时遇到了困难。

MemoryStream始终为空。

代码语言:javascript
复制
    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)

我该如何解决这个问题?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-18 15:05:16

在Default.aspx.cs中,您可以做一些问题的代码块中遗漏的相关操作:

代码语言:javascript
复制
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。方法文档:

代码语言:javascript
复制
/**
 * 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) {

(来自)

代码语言:javascript
复制
/**
 * 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的内容被写入内存流。

而且我看到你在用

代码语言:javascript
复制
byte[] bt = memoryStream.GetBuffer();

请不要这样!除非您确定您正确地解释了缓冲区内容(可能包含其他垃圾数据),否则请使用

代码语言:javascript
复制
byte[] bt = memoryStream.ToArray();

而不是。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17711070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档