【发布时间】: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.Read和PdfReader中是否有相同的方法?那么你可以使用while(PdfReader.Read()) -
感谢您的回答,不过我不会尝试,因为有人找到了问题的原因。
标签: c# pdf itextsharp