问题描述
我有两个代码:
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();
效果很好!该文件有46.451字节
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();
文件具有45.582字节. Acrobat Reader告诉我该文件已损坏.我在做什么错了?
The file has 45.582 bytes. Acrobat Reader tells me that the file is corrupted. What I'm doing wrong?
谢谢!
推荐答案
在您这样做的时候
output.WriteTo(new FileStream(fileOutput, FileMode.Create, System.IO.FileAccess.Write));
结果PDF尚未完成.因此,显然Acrobat Reader会抱怨.
the result PDF is not yet finished. Thus, obviously Acrobat Reader will complain.
要在内存流中保存完成的PDF,必须等到之后
To have the finished PDF in the memory stream, you have to wait until after
doc.Close();
默认情况下,这会隐式关闭您可能不需要的输出流.因此,您可能还想先将SetCloseStream(false)应用于PdfCopy.
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.
这篇关于MemoryStream看起来像是使用iTextSharp损坏了文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!