【问题标题】:Can't open a pdf using iTextSharp无法使用 iTextSharp 打开 pdf
【发布时间】:2015-06-29 14:03:24
【问题描述】:

我正在尝试使用 c# iTextSharp 库将 pdf 文件转换为文本文件。我的代码如下:

private void button2_Click(object sender, EventArgs e)
        {
            string FosPdf = @"D:\Public\temp\FOS.pdf";
            if (System.IO.File.Exists(FosPdf))
            {
                try
                {
                    StringBuilder text = new StringBuilder();
                    PdfReader pdfReader = new PdfReader(FosPdf);

                    for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                    {
                        ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                        string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
                        text.Append(System.Environment.NewLine);
                        text.Append("\n Page Number:" + page);
                        text.Append(System.Environment.NewLine);
                        currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                        text.Append(currentText);
                        pdfReader.Close();
                    }
                    string path = @"D:\Public\temp\FOSEtest.txt";
                    if (!System.IO.File.Exists(path))
                    {
                        // Create a file to write to. 
                        using (System.IO.StreamWriter sw = System.IO.File.CreateText(path))
                        {
                            sw.WriteLine("Test :");
                        }
                    }

                    pdftext.Text += text.ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message, "Error");
                }
            }
        }   

但是,当提取开始时,程序会在“for”的开头停止。错误是“无法访问已关闭的文件”。

所以我的猜测是 PdfReader 应该打开 pdf 阅读器但没有:知道为什么吗?

我也尝试在启动程序之前打开 pdf,但错误仍然存​​在。

提前感谢您的任何帮助

【问题讨论】:

  • 我们在XmlTextReader.ReadPdfReader 中是否有相同的方法?那么你可以使用while(PdfReader.Read())
  • 感谢您的回答,不过我不会尝试,因为有人找到了问题的原因。

标签: c# pdf itextsharp


【解决方案1】:

在你的 for 循环中,你关闭它

     pdfReader.Close();

【讨论】:

  • @LoukoumMira 不要与帮助你的人争论。将Close() 移到循环外并告诉我们问题是否已解决。给出的答案是正确的。您的评论不正确。
  • @Bruno Lowagie,确实,我很抱歉,我实际上正要说他是对的。所以谢谢你弗雷杜!
  • @LoukoumMira 在这种情况下,请接受答案。
猜你喜欢
  • 2016-12-18
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 2015-07-12
  • 2016-11-07
  • 1970-01-01
  • 2011-08-31
相关资源
最近更新 更多