我热烈欢迎...... 我有一个问题,我正在尝试将PDF转换为TXT,我无法保存txt文件?有人请帮帮我??
using System;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
namespace ZestawienieFaktur
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(@"D:\\faktury\\", "*.pdf");
foreach (string fp in filePaths)
{
ExtractTextFromPdf(fp);
}
}
public static string ExtractTextFromPdf(string path)
{
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}
string lines = text.ToString();
using (var file = new StreamWriter(@"D:\faktury\test1.txt"))
{
file.WriteLine(lines);
file.Close();
}
}
}
}
}
在文件夹中,我有几个不同名称的pdf文件。 我希望所有人都转换为txt的格式。 回答的大问题......
答案 0 :(得分:0)
您应该删除return
关键字,然后返回void
。它没有执行的原因是因为它在return
之后停止执行其余的代码。将其更改为:
public static void ExtractTextFromPdf(string path)
{
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}
string lines = "";
using(var file = new StreamWriter(path2))
{
file.WriteLine(lines);
file.Close();
}
}
}
希望它有所帮助!
答案 1 :(得分:0)
好的工作好朋友......
using System;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
namespace ZestawienieFaktur
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(@"D:\faktury\", "*.pdf");
foreach (string fp in filePaths)
{
ExtractTextFromPdf(fp);
}
}
public static string ExtractTextFromPdf(string path)
{
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}
string lines = text.ToString();
using (var file = new StreamWriter(@"D:\faktury\test1.txt"))
{
file.WriteLine(lines);
file.Close();
}
return lines;
}
}
}
}