Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

iTextSharp.NetCore 读取PDF文件中的文字

  1. User

    iTextSharp.NetCore 读取PDF文件中的文字

  2. Assistant

    以下是使用iTextSharp.NetCore读取PDF文件中的文字的示例代码:

    using iTextSharp.text.pdf;
    using iTextSharp.text.pdf.parser;
    
    public string ReadPdf(string filePath)
    {
        PdfReader reader = new PdfReader(filePath);
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= reader.NumberOfPages; i++)
        {
            sb.Append(PdfTextExtractor.GetTextFromPage(reader, i));
        }
        reader.Close();
        return sb.ToString();
    }
    

    该代码通过创建一个PdfReader对象读取PDF文件,使用PdfTextExtractor.GetTextFromPage方法从每一页获取文本,并将所有文本合并到一个StringBuilder对象中。最后,通过Close方法关闭PdfReader对象并返回合并的文本。

    请注意,使用iTextSharp需要安装NuGet包iTextSharp.NetCore。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.