我需要将一个 .pdf 文件转换成 .txt 文件,如何在 C# 中实现?
Ghostscript可以满足您的需求。下面是从pdf文件中提取文本到txt文件的命令(您可以从命令行运行它来测试它是否适用于您):
gswin32c.exe -q -dNODISPLAY -dSAFER -dDELAYBIND -dWRITESYSTEMDICT -dSIMPLE -c save -f ps2ascii.ps "test.pdf" -c quit >"test.txt"
请查看这里:codeproject:使用Ghostscript API将PDF转换为图像,了解如何在C#中使用ghostscript的详细信息。
Docotic.Pdf library可以从PDF文件中提取文本(无论格式如何)。
以下是一个示例代码,展示了如何从PDF文件中提取格式化文本并将其保存到另一个文件中。
public static void ExtractFormattedText(string pdfFile, string textFile)
{
using (PdfDocument doc = new PdfDocument(pdfFile))
{
string text = doc.GetTextWithFormatting();
File.WriteAllText(textFile, text);
}
}
此外,我们网站上还有一篇文章介绍了其他从PDF文件中提取文本的选项(链接)。
声明:我是Bit Miracle公司的供应商。
public void PDF_TEXT()
{
richTextBox1.Text = string.Empty;
ReadPdfFile(@"C:\Myfile.pdf"); //read pdf file from location
}
public void ReadPdfFile(string fileName)
{
string strText = string.Empty;
StringBuilder text = new StringBuilder();
try
{
PdfReader reader = new PdfReader((string)fileName);
if (File.Exists(fileName))
{
PdfReader pdfReader = new PdfReader(fileName);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
text.Append(currentText);
}
pdfReader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
richTextBox1.Text = text.ToString();
}
private void Save_TextFile_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
DialogResult messageResult = MessageBox.Show("Save this file into Text?", "Text File", MessageBoxButtons.OKCancel);
if (messageResult == DialogResult.Cancel)
{
}
else
{
sfd.Title = "Save As Textfile";
sfd.InitialDirectory = @"C:\";
sfd.Filter = "TextDocuments|*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
if (richTextBox1.Text != "")
{
richTextBox1.SaveFile(sfd.FileName, RichTextBoxStreamType.PlainText);
richTextBox1.Text = "";
MessageBox.Show("Text Saved Succesfully", "Text File");
}
else
{
MessageBox.Show("Please Upload Your Pdf", "Text File",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
}
}