且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PdfStamper是否正在处理输出流? (iTextSharp)

更新时间:2022-06-15 09:52:08

此并不是真正的答案,而是扩展@mkl所说的内容,请使用指令切换到,因为那些指令执行 try / finally 东西会自动为您提供。

This isn't really an answer but to expand upon what @mkl said, switch over to using directives since those perform the try/finally stuff for you automatically.

以下是我(以及可能使用iTextSharp的其他所有人)通常建议与iTextSharp进行交互的方式。外部 using 是BCL东西,在这种情况下, MemoryStream 和内部 using 语句是iTextSharp的东西。

Below is the way I (and probably everyone else that uses iTextSharp) would generally recommend to interact with iTextSharp. The outer using is BCL stuff, in this case the MemoryStream and the inner using statements are iTextSharp stuff.

//Will hold our raw PDF bytes
Byte[] result;

//BCL stuff first
using (var mem = new MemoryStream()) {

    //iText stuff in the middle
    using (var reader = new PdfReader(m_pdf)) {
        using (var stamper = new PdfStamper(reader, mem)) {
            // do stuff

        }
    }

    //iText is completely done and disposed of at this point
    //so we can now grab the raw bytes that represent a PDF
    result = mem.ToArray();
}

顺便说一句,不一定适用于OP,以防万一有人看到因此,几乎没有(并且几乎从不,我的意思是从来没有)是关闭基础流的一个很好的理由。您可以通过获取原始字节并再次写入来从流中读取数据。

As an aside, not necessarily for the OP but just in case someone else sees this, there is almost never (and by "almost never" I really mean "never") a good reason to not close the underlying stream. You can read from the stream by grabbing the raw bytes and writing to it again never makes sense.