Question

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!

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top