我正在使用PDFBox解析PDF,我正在尝试获取文本颜色。使用TextPosition属性,可以毫无问题地获得其他属性,如字体,大小和位置。这是我的操作方式:
@Override
protected void writeString (String string, List<TextPosition> textPositions) {
for (TextPosition textPosition : textPositions) {
System.out.println(textPosition.getFont());
System.out.println(textPosition.getFontSizeInPt());
System.out.println(textPosition.getXDirAdj() + ", " + textPosition.getYDirAdj());
}
但是,我无法检索文本的颜色。我已经在Google上搜索了一种解决方案,但到目前为止没有任何效果。我看到的每个教程似乎都在使用旧版本的PDFBox。我没有这些人正在使用的几种方法。例如,在一个SO问题中,他们建议使用以下代码:
@Override
protected void processTextPosition(TextPosition text) {
try {
PDGraphicsState graphicsState = getGraphicsState();
System.out.println("R = " + graphicsState.getNonStrokingColor().getJavaColor().getRed());
System.out.println("G = " + graphicsState.getNonStrokingColor().getJavaColor().getGreen());
System.out.println("B = " + graphicsState.getNonStrokingColor().getJavaColor().getBlue());
}
catch (IOException ioe) {}
}
[当我尝试使用它时,IntelliJ告诉我“ getJavaColor()”未定义。我也尝试过使用此代码:
@Override
protected void processTextPosition(TextPosition text) {
try {
PDGraphicsState graphicsState = getGraphicsState();
System.out.println("R = " + graphicsState.getNonStrokingColor().toRGB());
}
catch (IOException ioe) {System.out.println(ioe); }
}
并且,尽管按预期方式以及预期的次数调用了该方法,但是即使在我的PDF文件中我有黑色文本和红色文本,它也总是打印0。
这是我的Maven依赖项:
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/fontbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox-tools -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.17</version>
</dependency>
</dependencies>
感谢您的任何帮助
显然在PDFBox 2.0.0+版本中,您需要添加以下代码行:
addOperator(new SetStrokingColorSpace());
addOperator(new SetNonStrokingColorSpace());
addOperator(new SetStrokingDeviceCMYKColor());
addOperator(new SetNonStrokingDeviceCMYKColor());
addOperator(new SetNonStrokingDeviceRGBColor());
addOperator(new SetStrokingDeviceRGBColor());
addOperator(new SetNonStrokingDeviceGrayColor());
addOperator(new SetStrokingDeviceGrayColor());
addOperator(new SetStrokingColor());
addOperator(new SetStrokingColorN());
addOperator(new SetNonStrokingColor());
addOperator(new SetNonStrokingColorN());
到您的PDFTextStripper覆盖的类构造函数。现在,如果您使用:
@Override
protected void processTextPosition (TextPosition textPosition) {
try {
PDGraphicsState graphicsState = getGraphicsState();
System.out.println(graphicsState.getNonStrokingColor().toRGB());
}
catch (Exception ioe) {}
}
它实际打印出实际值。