您使用的PDFTextStripper
类记录在案(参见它的 JavaDoc 注释),如下所示:
* This class will take a pdf document and strip out all of the text and ignore the
* formatting and such.
因此,要获取特定的字体信息,您必须对其进行一些更改。
字体信息在这个类中一直可用,只有在输出一行时才被丢弃,看看它的来源:
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();
[...]
}
............
该TextPosition
列表中的实例line
仍然具有所有可用的格式信息,其中包括使用的字体,只是在“规范化”line
时它被简化为纯字符。
因此,要保留字体信息,您有不同的选择,具体取决于您要如何检索字体信息:
如果您想通过以下方式继续在单个字符串中检索所有页面内容信息(包括字体)getText
:您更改方法
private List<String> normalize(List<TextPosition> line, boolean isRtlDominant, boolean hasRtl)
在字体更改时包含您选择的一些字体标签(例如[Arial]
)。不幸的是,这种方法是私有的。因此,您必须复制整个PDFTextStripper
类并更改副本的代码。
如果您想以不同的结构(例如 as List<List<TextPosition>>
)检索特定的字体信息,您可以从 派生您自己的剥离器类PDFTextStripper
,添加一些您想要的类型的变量,并覆盖上面提到的protected
方法writePage
,复制它并仅在之前或之后增强它线
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
,检索纯文本作为结果,并通过新变量访问附加数据