我是 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 页面仅包含的信息
宋体和宋体。
最佳答案
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();
[...]
}
............
TextPosition
该列表中的实例 line
仅在“规范化”line
时仍然拥有所有可用的格式信息,其中包括使用的字体它被简化为纯字符。
因此,要保留字体信息,您有不同的选择,具体取决于您希望如何检索字体信息:
如果您想通过
getText
继续检索单个字符串中的所有页面内容信息(包括字体) :你改变方法private List<String> normalize(List<TextPosition> line, boolean isRtlDominant, boolean hasRtl)
每当字体发生变化时,包含您选择的一些字体标签(例如
[Arial]
)。不幸的是这个方法是私有(private)的。因此,您必须复制整个PDFTextStripper
类并更改副本的代码。如果您想以不同的结构检索特定字体信息(例如
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
为例,检索纯文本作为结果,并通过新变量访问附加数据
关于java - 使用 PDFBox 获取 PDF 文本的字体信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20114979/