开发者

Simple PDF created with iTextSharp cannot be opened by Acrobat Reader?

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜