5
votes

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

2
Any ideas ? I guess this is just something very easy, something like my very stupid mistake but I just cant see it... - Rasto
I runned your code and didn't get any error, which version of ITextSharp are you using ? - dada686
Not even when trying to open the generated file ?? I don't get error when I run c# code, only when I open generated file. - Rasto
no, it showed the "aaa" at the bottom perfectly fine - dada686
@dada686: strange... What may cause it ? I'll try to delete the file and restart VS, then run it again and generate the PDF. - Rasto

2 Answers

3
votes

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

2
votes

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