views:

82

answers:

2

I create simple test PDF document using iTextSharp. I'm just using PdfContentByte to show some text. This is the code:

    Document document = new Document();
    Stream outStream = new FileStream("D:\\aaa\\test.pdf", FileMode.OpenOrCreate);
    PdfWriter writer = PdfWriter.GetInstance(document, outStream);
    document.Open();
    PdfContentByte to = writer.DirectContent;
    to.BeginText();
    to.SetFontAndSize(BaseFont.CreateFont(), 12);
    to.SetTextMatrix(0, 0);
    to.ShowText("aaa");
    to.EndText();
    document.Close();
    outStream.Close();

The file is created but when I try to open it(using Acrobat Reader), all I get is following message:

There was an error opening this document. There was a problem reading this document (14).

Where is the problem ? How do I fix it? Thank you

+1  A: 

I can't seem to replicate the problem you're encountering, but please take into account potential leaks of resources due to any exceptional conditions you may encounter and properly Dispose() those objects as such:

    using (Stream outStream = new FileStream("D:\\aaa\\test.pdf", FileMode.OpenOrCreate))
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.GetInstance(document, outStream);

        document.Open();
        try
        {
            PdfContentByte to = writer.DirectContent;

            to.BeginText();
            try
            {
                to.SetFontAndSize(BaseFont.CreateFont(), 12);
                to.SetTextMatrix(0, 0);
                to.ShowText("aaa");
            }
            finally
            {
                to.EndText();
            }
        }
        finally
        {
            document.Close();
        }
    }
Jesse C. Slicer
A: 

Problem was solved after restarting VS. No code change was made.

drasto