Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

c# - iTextSharp + FileStream = Corrupt PDF file

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):

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().

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.

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...