PdfReader from MemoryStream()

2019-08-12 05:01发布

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 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 .net4

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

Thanks in advance.

3条回答
Summer. ? 凉城
2楼-- · 2019-08-12 05:20

If you want to just open the pdf in browser using bytes then do this :

public void ReturnPDF(byte[] contents, string attachmentFilename)
        {
            var response = HttpContext.Current.Response;
            try
            {
                if (!string.IsNullOrEmpty(attachmentFilename))
                {
                    response.ContentType = "application/pdf";
                    response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
                }

                response.ContentType = "application/pdf";
                response.BinaryWrite(contents);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                response.End();
                response.Flush();
                response.Clear();
            }


        }
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-12 05:23

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);
查看更多
走好不送
4楼-- · 2019-08-12 05:33

Maybe a bit late. Try to set the streams position to 0.

...
stream.Flush(); // Don't know if this is necessary
stream.Position = 0;
PdfReader reader = new PdfReader(stream.ToArray());
...
查看更多
登录 后发表回答