C#提取PDF文件中的文字

在C#中提取PDF文件中的文字,你可以使用一些流行的库,如iTextSharp、PdfSharp(主要用于创建和修改PDF,但提取文字能力有限),或者更为强大的PDFBox.net(基于Apache PDFBox的.NET端口,尽管它主要是Java项目,但可以通过.NET Core的JNI或类似技术使用)。然而,对于C#来说,iTextSharp是最常见和直接的选择。

使用iTextSharp提取PDF中的文字

首先,你需要在你的C#项目中安装iTextSharp。如果你使用NuGet包管理器,可以通过以下命令安装:

Install-Package iTextSharp

或者,如果你使用的是.NET Core的命令行界面(CLI),可以使用:

dotnet add package itextsharp

以下是一个使用iTextSharp提取PDF文件中所有文字的基本示例:

using System;  
using System.IO;  
using iTextSharp.text.pdf;  
using iTextSharp.text.pdf.parser;  
  
class Program  
{  
    static void Main(string[] args)  
    {  
        string pdfFilePath = @"path\to\your\file.pdf";  
          
        PdfReader reader = new PdfReader(pdfFilePath);  
        try  
        {  
            for (int page = 1; page <= reader.NumberOfPages; page++)  
            {  
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();  
                string text = PdfTextExtractor.GetTextFromPage(reader, page, strategy);  
                Console.WriteLine($"Page {page}: {text}");  
            }  
        }  
        finally  
        {  
            reader.Close();  
        }  
    }  
}

这段代码首先创建了一个PdfReader实例来读取PDF文件。然后,它遍历PDF的每一页,使用PdfTextExtractor.GetTextFromPage方法和SimpleTextExtractionStrategy策略来提取并打印每页的文字。最后,确保在结束时关闭PdfReader实例以释放资源。

注意

  • 某些PDF文件可能包含复杂的布局、图像中的文字或加密的内容,这些情况可能需要更高级的提取策略或技术。
  • iTextSharp和其他库可能受到其许可证协议的约束,特别是商业用途。请确保你遵守了所使用库的许可要求。
  • 对于图像中的文字,你可能需要使用OCR(光学字符识别)技术来提取。这通常超出了纯PDF处理库的范畴,并需要额外的工具或库。
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C#调用itext读取pdf文件提取文本的示例代码: ```csharp using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Parser; using iText.Kernel.Pdf.Canvas.Parser.Listener; using System.Text; public static string ExtractTextFromPDF(string filepath) { StringBuilder sb = new StringBuilder(); using (PdfReader reader = new PdfReader(filepath)) { using (PdfDocument pdfDoc = new PdfDocument(reader)) { for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) { PdfPage page = pdfDoc.GetPage(i); ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); string text = PdfTextExtractor.GetTextFromPage(page, strategy); sb.Append(text); } } } return sb.ToString(); } ``` 为了实现相邻文本距离超过一个字宽度的用空格补齐的功能,我们可以在获取文本时添加一些额外的处理: ```csharp public static string ExtractTextFromPDF(string filepath) { StringBuilder sb = new StringBuilder(); using (PdfReader reader = new PdfReader(filepath)) { using (PdfDocument pdfDoc = new PdfDocument(reader)) { for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) { PdfPage page = pdfDoc.GetPage(i); CustomTextExtractionStrategy strategy = new CustomTextExtractionStrategy(); string text = PdfTextExtractor.GetTextFromPage(page, strategy); // 将相邻文本距离超过一个字宽度的用空格补齐 text = strategy.FillInSpaceBetweenWords(text); sb.Append(text); } } } return sb.ToString(); } public class CustomTextExtractionStrategy : LocationTextExtractionStrategy { // 记录当前字符的左上角坐标 private Vector lastStart; public override void BeginTextBlock() { base.BeginTextBlock(); lastStart = null; } public override void RenderText(TextRenderInfo renderInfo) { base.RenderText(renderInfo); Vector start = renderInfo.GetDescentLine().GetStartPoint(); Vector end = renderInfo.GetAscentLine().GetEndPoint(); if (lastStart != null) { // 计算当前字符的左上角坐标和上一个字符的右上角坐标之间的距离 float distance = start.Subtract(lastStart).Length(); // 如果距离大于一个字宽度,则认为间需要插入一个空格 if (distance > renderInfo.GetSingleSpaceWidth()) { AppendText(" "); } } AppendText(renderInfo.GetText()); lastStart = start; } // 将相邻文本距离超过一个字宽度的用空格补齐 public string FillInSpaceBetweenWords(string text) { StringBuilder sb = new StringBuilder(); char[] chars = text.ToCharArray(); for (int i = 0; i < chars.Length; i++) { sb.Append(chars[i]); if (i < chars.Length - 1) { // 计算当前字符和下一个字符的距离 float distance = GetDistanceBetweenChars(chars[i], chars[i + 1]); // 如果距离大于一个字宽度,则认为间需要插入一个空格 if (distance > GetSingleSpaceWidth()) { sb.Append(" "); } } } return sb.ToString(); } // 获取两个字符之间的距离 private float GetDistanceBetweenChars(char c1, char c2) { Glyph glyph1 = font.GetGlyph(c1); Glyph glyph2 = font.GetGlyph(c2); return glyph1.GetWidth() + glyph2.GetWidth() - glyph1.GetBoundingBox().GetRight(); } // 获取一个空格的宽度 public float GetSingleSpaceWidth() { Glyph glyph = font.GetGlyph(' '); return glyph.GetWidth(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值