Filth said:

Hi,

I've just starting using iTextSharp in a code behind page, but when I run it, it just shows a empty pdf.

I was wondering if anyone could see anything crazy that I have or haven't done?

The code in my page_load event is:

MemoryStream m = new MemoryStream();

Document document = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);

try

{

Response.ContentType = "application/pdf";

PdfWriter.GetInstance(document, m);

document.Open();

document.Add(new Paragraph(DateTime.Now.ToString()));

document.Add(new Paragraph("This is another test"));

document.Add(new Paragraph("Yet another test"));

}

catch (DocumentException ex)

{

Console.Error.WriteLine(ex.StackTrace);

Console.Error.WriteLine(ex.Message);

}

// step 5: Close document

document.Close();

// step 6: Write pdf bytes to outputstream

Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);

Response.OutputStream.Flush();

Response.OutputStream.Close();

You are trying to use iTextSharp in a web application so you can use ASP.NET's response stream directly to write the PDF.  Your code would look something like:

            this.Response.ContentType = "application/pdf";

            Document doc = new Document();

            PdfWriter writer = PdfWriter.GetInstance( doc, this.Response.OutputStream );

            try
            {
                doc.Open();
                doc.Add( new Paragraph( DateTime.Now.ToString() ) );
                doc.Add( new Paragraph( "This is a test" ) );
            }
            finally
            {
                doc.Close();
                writer.Close();
            }