使用c#中的iTextSharp读取中文文本字符

本文关键字:中文 文本 字符 读取 iTextSharp 中的 使用 | 更新日期: 2023-09-27 18:20:29

我使用iTextSharp读取pdf文件。我可以阅读英文文本,但对于中文,我会打问号,我如何使用iTextSharp阅读汉字。

coverNoteFilePath = @"D:'Temp'cc8a12e6-399a-4146-81ac-e49eb67e7e1b'CoverNote.pdf";
    try
    {
        PdfReader reader = new PdfReader(coverNoteFilePath);
        for (int page = 1; page <= reader.NumberOfPages; page++)
        {
            ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
            String s = PdfTextExtractor.GetTextFromPage(reader, page, its);
            s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
            coverNoteContent = coverNoteContent + s;
        }
        reader.Close();
        Response.Write(coverNoteContent);
    }

使用c#中的iTextSharp读取中文文本字符

尝试将ASCIIEncoding替换为其他编码类之一(例如UTF8Encoding)。我想PDF文档知道它们使用的是哪种编码,所以您可能能够在PdfReader对象中找到正确的编码。值得检查。

来自MSDN:

ASCIIEncoding对应于Windows代码页20127。由于ASCII是一种7位编码,ASCII字符被限制为最低的128个Unicode字符,从U+0000到U+007F。如果使用Encoding.ASCII属性或ASCIIEncoding构造函数返回的默认编码器,则在执行编码操作之前,该范围之外的字符将替换为问号(?)。因为ASCIIEncoding类只支持有限的字符集,所以UTF8Encoding、UnicodeEncoding和UTF32Encoding类更适合全球化应用程序。