MemoryStream looks like corrupt the file using iTextSharp

一笑奈何 提交于 2020-01-06 14:11:51

问题


I have two codes:

string fileInput = @"c:\temp\input.pdf";
string fileOutput = @"c:\temp\saida.pdf";

PdfReader reader = new PdfReader(fileInput);

Stream output = new System.IO.FileStream(fileOutput, System.IO.FileMode.Create);

Document doc = new Document();
PdfCopy writer = new PdfCopy(doc, output);

doc.Open();
PdfImportedPage pagina = writer.GetImportedPage(reader, 23);
writer.AddPage(pagina);

doc.Close();

output.Close();

It works very well! The file has 46.451 bytes

But I need use Memory instead of Files. So I tried the next code:

string fileInput = @"c:\temp\input.pdf";
string fileOutput = @"c:\temp\saida.pdf";

PdfReader reader = new PdfReader(fileInput);

//Stream output = new System.IO.FileStream(fileOutput, System.IO.FileMode.Create);
MemoryStream output = new MemoryStream();

Document doc = new Document();
PdfCopy writer = new PdfCopy(doc, output);

doc.Open();
PdfImportedPage pagina = writer.GetImportedPage(reader, 23);
writer.AddPage(pagina);

//Added line. Just to compare...
output.WriteTo(new FileStream(fileOutput, FileMode.Create, System.IO.FileAccess.Write));

doc.Close();

output.Close();

The file has 45.582 bytes. Acrobat Reader tells me that the file is corrupted. What I'm doing wrong?

Thanks!


回答1:


At the time you do

output.WriteTo(new FileStream(fileOutput, FileMode.Create, System.IO.FileAccess.Write));

the result PDF is not yet finished. Thus, obviously Acrobat Reader will complain.

To have the finished PDF in the memory stream, you have to wait until after

doc.Close();

This by default implicitly closes the output stream which might not be desired by you. Thus, you also might want to apply SetCloseStream(false) to the PdfCopy before.



来源:https://stackoverflow.com/questions/19618756/memorystream-looks-like-corrupt-the-file-using-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!