无法使用 iTextSharp 打开 pdf
Can't open a pdf using 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");
}
}
}
但是,当提取开始时,程序在 "for" 的开头停止。错误是它是"Impossible to access a closed file"。
所以我的猜测是 PdfReader
应该打开 pdf reader 但没有:知道为什么吗?
我也试过在启动程序之前让 pdf 打开,错误仍然存在。
在此先感谢您的任何帮助
在你的 for 循环中,你关闭它
pdfReader.Close();
我正在尝试使用 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" 的开头停止。错误是它是"Impossible to access a closed file"。
所以我的猜测是 PdfReader
应该打开 pdf reader 但没有:知道为什么吗?
我也试过在启动程序之前让 pdf 打开,错误仍然存在。
在此先感谢您的任何帮助
在你的 for 循环中,你关闭它
pdfReader.Close();