【问题标题】:Simple PDF created with iTextSharp cannot be opened by Acrobat Reader?Acrobat Reader 无法打开使用 iTextSharp 创建的简单 PDF?
【发布时间】:2011-03-29 11:08:24
【问题描述】:

我使用 iTextSharp 创建简单的测试 PDF 文档。我只是使用 PdfContentByte 来显示一些文本。这是代码:

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

文件已创建,但当我尝试打开它(使用 Acrobat Reader)时,我得到的只是以下消息:

打开此页面时出错 文档。阅读有问题 本文档 (14)。

问题出在哪里?我如何解决它?谢谢

【问题讨论】:

  • 有什么想法吗?我想这只是一件很简单的事情,就像我的非常愚蠢的错误,但我就是看不到它......
  • 我运行了您的代码,没有收到任何错误,您使用的是哪个版本的 ITextSharp?
  • 即使尝试打开生成的文件也不行??运行 c# 代码时不会出错,只有在打开生成的文件时才会出错。
  • 不,它在底部显示“aaa”非常好
  • @dada686:奇怪...可能是什么原因造成的?我会尝试删除文件并重新启动VS,然后再次运行并生成PDF。

标签: c# pdf pdf-generation itextsharp itext


【解决方案1】:

重启VS后问题解决。没有进行任何代码更改。

【讨论】:

    【解决方案2】:

    我似乎无法复制您遇到的问题,但请考虑到由于您可能遇到的任何异常情况而导致的潜在资源泄漏,并正确地Dispose() 这些对象:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 2017-04-29
      • 2016-05-18
      • 1970-01-01
      相关资源
      最近更新 更多