c# - iTextSharp + FileStream = Corrupt PDF file -
I am trying to create a PDF file with iTextSharp. My attempt is to write PDF content in MemoryStream, so I can write the results both in the file and database blob. File is created, it is about 21 kb size and it looks like a PDF while doing Notepad ++ but my PDF Viewer says it is interrupted. Here's a small snippet of code (not just trying to write on a file, not for the database):
document myDocument = new document (); MemoryStream myMemoryStream = New MemoryStream (); PdfWriter myPDFWriter = PdfWriter.GetInstance (myDocument, myMemoryStream); MyDocument.Open (); // Content of PDF (FileStream FS = File is inserted here by using Create Create ("D: \\ ... \\ aTestFile.pdf") {myMemoryStream.WriteTo (fs); } MyMemoryStream.Close ();
= "Text">
I think your problem was that You were not adding content to your PDF properly This document is done through the add () method and you can complete the call by documenting. Stop it ().
When you call the document. Close () However, your MemoryStream also turns off so that you are not able to write your filestream as much as you have. You can store the content of your memory stream in 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 your pdf content here ... myDocument.Add (new paragraph ("I hope this works for you.")); // We add stuff to our pdf. MyDocument.Close (); Byte [] Content = myMemoryStream.ToArray (); // Write the PDF from the memory stream (filestream fs = create the file ("aTestFile.pdf")) {fs.Write (content, 0, (int) content.Length); }}
Comments
Post a Comment