PdfReader from MemoryStream()

Dave picture Dave · Feb 18, 2013 · Viewed 13.5k times · Source

Can anyone give me an example of how to get a PdfReader from a MemoryStream? I can see that the PdfReader class has a couple of methods which look like likely candidates (GetStreamBytes & GetStreamBytesRaw), however these seem to want iText-specific streams, mine is just a regular Byte[] or MemoryStream.

This is using C# and .NET 4.

iTextSharp.text.pdf.PdfReader rdr = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw

Answer

voidmain picture voidmain · Sep 18, 2014

You can create a PdfReader from a MemoryStream, so long as the MemoryStream is a valid PDF object. If the MemoryStream is a valid PDF object, then one way to initiate the PdfReader is this way:

PdfReader _reader = new PdfReader((byte[])_memoryStream.ToArray());

In the code below, the PdfReader is initialized from .Net Resource which is returned as a byte[] when called from the Properties.Resources object, so the Resource and the MemoryStream are returning the same type to the PdfReader, a byte[]. I then create a PdfStamper object from the PdfReader object, and use a MemoryStream as the resulting container for the PdfStamper.

PdfReader _srcDoc = new PdfReader(Properties.Resources.Resource1);
MemoryStream _output = new MemoryStream();
PdfStamper _scratchDoc = new PdfStamper(_srcDoc, _output);