无法使用iTextSharp打开pdf

时间:2015-06-29 14:03:25

标签: c# pdf itextsharp

我正在尝试使用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");
                }
            }
        }   

然而,当提取开始时,程序在&#34; for&#34;的开头停止。错误在于它无法访问已关闭的文件&#34;。

所以我的猜测是PdfReader应该打开pdf阅读器,但不知道为什么?

我还试图在启动程序之前保持pdf打开,错误保持不变。

提前感谢您提供任何帮助

1 个答案:

答案 0 :(得分:2)

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

     pdfReader.Close();
相关问题