首页 > 解决方案 > iTextSharp 仅返回特定 PDF 文件的空格字符串

问题描述

我正在测试这个简单的代码:

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PDF_TXT2
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {

            string path = args[0];

            string pathFileName = System.IO.Path.GetFileNameWithoutExtension(path);

            string pathFolder = System.IO.Path.GetDirectoryName(path);

            PdfReader reader = new PdfReader(path);

            string text = string.Empty;
            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                text += PdfTextExtractor.GetTextFromPage(reader, page);
            }
            reader.Close();

            Clipboard.SetText(text);
            MessageBox.Show(text);
        }
    }
}

这个特定的PDF文件会导致一个空字符串。实际上不是空的,而是充满了空格。

你能帮我理解为什么吗?

非常感谢!

标签: pdfitexttext-extraction

解决方案


PDF 中的字体有这个条目

/ToUnicode/Identity-H

ToUnicode的值是名称 Identity-H

但是,根据 PDF 规范,ToUnicode的值必须是一个

ToUnicode(可选)包含将字符代码映射到 Unicode 值的 CMap 文件的流(参见 9.10,“文本内容的提取”)。

因此,您文件中的ToUnicode映射无效,这可能导致文本提取期间出现任意错误。


推荐阅读