【问题标题】:Font information of text in PDF using PDFBox使用 PDFBox 的 PDF 中文本的字体信息
【发布时间】:2013-11-21 07:32:10
【问题描述】:

我是 Apache PDFBox 库的新手。

我想将字体信息映射到 PDF 段落

我已经通过Questios How to extract font styles of text contents using pdfbox?

但它没有提供关于哪个段落以哪种字体书写的信息。

例如,如果我的页面包含文本:

para1:宋体

para2:Times New Roman

那么我应该能够得到para1用Arial写而para2用Times New Roman写的信息。

上述问题中提出的解决方案给出了 PDF 页面仅包含的信息

arial and times new roman.

【问题讨论】:

标签: java pdfbox text-extraction pdf-parsing


【解决方案1】:

您使用的 PDFTextStripper 类记录如下(参见其 JavaDoc 注释):

* This class will take a pdf document and strip out all of the text and ignore the
* formatting and such.

因此,要获取特定的字体信息,您必须对其进行一些更改。

字体信息在这个类中一直可用,只在输出一行时丢弃,看看它的source

protected void writePage() throws IOException
{
    [...]
    for( int i = 0; i < charactersByArticle.size(); i++)
    {
        [...]
        List<TextPosition> line = new ArrayList<TextPosition>();
        [...]
        while( textIter.hasNext() )
        {
            [...]
            if( lastPosition != null )
            {
                [...]
                if(!overlap(positionY, positionHeight, maxYForLine, maxHeightForLine))
                {
                    writeLine(normalize(line,isRtlDominant,hasRtl),isRtlDominant);
                    line.clear();
                    [...]
                }
............

该列表line 中的TextPosition 实例仍然具有所有可用的格式信息,其中包括所使用的字体,只是在“规范化”line 时它被简化为纯字符。

因此,要保留字体信息,您有不同的选择,具体取决于您要如何检索字体信息:

  • 如果你想通过getText继续检索单个字符串中的所有页面内容信息(包括字体):你改变方法

    private List<String> normalize(List<TextPosition> line, boolean isRtlDominant, boolean hasRtl)
    

    在字体更改时包含您选择的一些字体标签(例如[Arial])。不幸的是,这种方法是私有的。因此,您必须复制整个PDFTextStripper 类并更改副本的代码。

  • 如果你想在不同的结构中检索特定的字体信息(例如List&lt;List&lt;TextPosition&gt;&gt;),你可以从PDFTextStripper派生你自己的剥离器类,添加一些你想要的类型的变量,然后覆盖protected方法@上面提到的987654337@,复制它,只在行前或行后进行增强

    writeLine(normalize(line,isRtlDominant,hasRtl),isRtlDominant);
    

    使用代码将信息添加到您的新变量中。例如

    public class MyPDFTextStripper extends PDFTextStripper
    {
        public List<List<TextPosition>> myLines = new ArrayList<List<TextPosition>>();
        [...]
                    if(!overlap(positionY, positionHeight, maxYForLine, maxHeightForLine))
                    {
                        writeLine(normalize(line,isRtlDominant,hasRtl),isRtlDominant);
                        myLines.add(new ArrayList<TextPosition>(line));
                        line.clear();
                        [...]
                    }
    

    现在您可以调用getText 来获取MyPDFTextStripper 的实例,检索纯文本作为结果,并通过新变量访问其他数据

【讨论】:

    【解决方案2】:

    要添加更多字体,而不是库字体,因此您需要专门添加字体文件。

    【讨论】:

    • 我只想知道哪个文字是用哪个字体写的,我的电脑上已经安装了字体。
    猜你喜欢
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2013-09-23
    相关资源
    最近更新 更多