C# iTextSharp + FileStream = 损坏的 PDF 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2186817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:12:31  来源:igfitidea点击:

iTextSharp + FileStream = Corrupt PDF file

c#pdfitextsharpfilestreammemorystream

提问by Norbert

I am trying to create a pdf file with iTextSharp. My attempt writes the content of the pdf to a MemoryStream so I can write the result both into file and a database BLOB. The file gets created, has a size of about 21kB and it looks like a pdf when opend with Notepad++. But my PDF viewer says it's currupted. Here is a little code snippet (only tries to write to a file, not to a database):

我正在尝试使用 iTextSharp 创建一个 pdf 文件。我的尝试将 pdf 的内容写入 MemoryStream,以便我可以将结果写入文件和数据库 BLOB。该文件已创建,大小约为 21kB,使用 Notepad++ 打开时看起来像 pdf。但是我的 PDF 查看器说它已损坏。这是一个小代码片段(仅尝试写入文件,而不是数据库):

Document myDocument = new Document();
MemoryStream myMemoryStream = new MemoryStream();
PdfWriter myPDFWriter = PdfWriter.GetInstance(myDocument, myMemoryStream);
myDocument.Open();
// Content of the pdf gets inserted here
using (FileStream fs = File.Create("D:\...\aTestFile.pdf"))
{
    myMemoryStream.WriteTo(fs);
}
myMemoryStream.Close();

Where is the mistake I make?

我犯的错误在哪里?

Thank you, Norbert

谢谢你,诺伯特

采纳答案by Jay Riggs

I think your problem was that you weren't properly adding content to your PDF. This is done through the Document.Add() method and you finish up by calling Document.Close().

我认为您的问题是您没有正确地向 PDF 添加内容。这是通过 Document.Add() 方法完成的,您可以通过调用 Document.Close() 完成。

When you call Document.Close() however, your MemoryStream also closes so you won't be able to write it to your FileStream as you have. You can get around this by storing the content of your MemoryStream to a byte array.

但是,当您调用 Document.Close() 时,您的 MemoryStream 也会关闭,因此您将无法将其写入 FileStream。您可以通过将 MemoryStream 的内容存储到字节数组来解决此问题。

The following code snippet works for me:

以下代码片段对我有用:

using (MemoryStream myMemoryStream = new MemoryStream()) {
    Document myDocument = new Document();
    PdfWriter myPDFWriter = PdfWriter.GetInstance(myDocument, myMemoryStream);

    myDocument.Open();

    // Add to content to your PDF here...
    myDocument.Add(new Paragraph("I hope this works for you."));

    // We're done adding stuff to our PDF.
    myDocument.Close();

    byte[] content = myMemoryStream.ToArray();

    // Write out PDF from memory stream.
    using (FileStream fs = File.Create("aTestFile.pdf")) {
        fs.Write(content, 0, (int)content.Length);
    }
}

回答by matt

Just some thoughts - what happens if you replace the memory stream with a file stream? Does this give you the result you need? This will at least tell you where the problem could be.

只是一些想法 - 如果用文件流替换内存流会发生什么?这是否为您提供了所需的结果?这至少会告诉您问题可能出在哪里。

If this does work, how do the files differ (in size and binary representation)?

如果这样做有效,文件有何不同(大小和二进制表示)?

Just a guess, but have you tried seeking to the beginning of the memory stream before writing?

只是一个猜测,但您是否尝试过在写入之前寻找内存流的开头?

myMemoryStream.Seek(0, SeekOrigin.Begin);

回答by wsanville

Try double checking your code that manipulates the PDF with iText. Make sure you're calling the appropriate EndText method of any PdfContentByte objects, and make sure you call myDocument.Close() before writing the file to disk. Those are things I've had problems with in the past when generating PDFs with iTextSharp.

尝试仔细检查使用 iText 操作 PDF 的代码。确保您正在调用任何 PdfContentByte 对象的适当 EndText 方法,并确保在将文件写入磁盘之前调用 myDocument.Close()。这些是我过去在使用 iTextSharp 生成 PDF 时遇到的问题。

回答by vivek anand

documentobject.Close();
using (FileStream fs = System.IO.File.Create(path)){                        
    Memorystreamobject.WriteTo(fs);
}         

回答by Oluwasayo Babalola

I had similar issue. My file gets downloaded but the file size will be 13Bytes. I resolved the issue when I used binary writer to write my file

我有类似的问题。我的文件被下载,但文件大小为 13 字节。当我使用二进制编写器编写我的文件时,我解决了这个问题

byte[] bytes = new byte[0];
//pass in your API response into the bytes initialized

using (StreamWriter streamWriter = new StreamWriter(FilePath, true))
{
   BinaryWriter binaryWriter = new BinaryWriter(streamWriter.BaseStream);
   binaryWriter.Write(bytes);
}