Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 493
Norbert Avatar asked Feb 02 '10 19:02

Norbert


2 Answers

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

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);
}
like image 184
Oluwasayo Babalola Avatar answered Oct 20 '22 00:10

Oluwasayo Babalola


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);
    }
}
like image 43
Jay Riggs Avatar answered Oct 20 '22 00:10

Jay Riggs