I am trying to convert a pdf file to a text one, using the c# iTextSharp library. My code is the one below :
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");
}
}
}
However, the program stops at the beginning of the "for", when the extraction starts. The error is that it is "Impossible to access a closed file".
So my guess is that PdfReader is supposed to open the pdf reader but doesn't : any idea why ?
I've also tried to leave the pdf open before launching the program, the error stays the same.
Thanks in advance for any kind of help
XmlTextReader.ReadinPdfReader? then you can usewhile(PdfReader.Read())- M.kazem Akhgary