我正在寻找实现Java解决方案的最简单方法,该解决方案与
pdftotext -layout FILE
在linux机器上。 (当然它也应该便宜)
我只是尝试了一些IText,PDFBox和PDFTextStream的代码段。到目前为止,最准确的解决方案是PDFTextStream,它使用VisualOutputTarget很好地表示了我的文件。
因此,我的列布局被认为是正确的,并且能够使用它。
但是,也应该有针对IText的解决方案吗?
我发现的每个简单代码段都会产生混乱的普通排序字符串(行/列/行混乱)。是否有任何解决方案可能更容易且可能不涉及自己的战略?还是有我可以使用的开源策略?
//我遵循mkl的说明,并编写并拥有如下的策略对象:
package com.test.pdfextractiontest.itext;
import ...
public class MyLocationTextExtractionStrategy implements TextExtractionStrategy {
/** set to true for debugging */
static boolean DUMP_STATE = false;
/** a summary of all found text */
private final List<TextChunk> locationalResult = new ArrayList<TextChunk>();
public MyLocationTextExtractionStrategy() {
}
@Override
public void beginTextBlock() {
}
@Override
public void endTextBlock() {
}
private boolean startsWithSpace(final String str) {
if (str.length() == 0) {
return false;
}
return str.charAt(0) == ' ';
}
private boolean endsWithSpace(final String str) {
if (str.length() == 0) {
return false;
}
return str.charAt(str.length() - 1) == ' ';
}
private List<TextChunk> filterTextChunks(final List<TextChunk> textChunks, final TextChunkFilter filter) {
if (filter == null) {
return textChunks;
}
final List<TextChunk> filtered = new ArrayList<TextChunk>();
for (final TextChunk textChunk : textChunks) {
if (filter.accept(textChunk)) {
filtered.add(textChunk);
}
}
return filtered;
}
protected boolean isChunkAtWordBoundary(final TextChunk chunk, final TextChunk previousChunk) {
final float dist = chunk.distanceFromEndOf(previousChunk);
if (dist < -chunk.getCharSpaceWidth() || dist > chunk.getCharSpaceWidth() / 2.0f) {
return true;
}
return false;
}
public String getResultantText(final TextChunkFilter chunkFilter) {
if (DUMP_STATE) {
dumpState();
}
final List<TextChunk> filteredTextChunks = filterTextChunks(this.locationalResult, chunkFilter);
Collections.sort(filteredTextChunks);
final StringBuffer sb = new StringBuffer();
TextChunk lastChunk = null;
for (final TextChunk chunk : filteredTextChunks) {
if (lastChunk == null) {
sb.append(chunk.text);
} else {
if (chunk.sameLine(lastChunk)) {
if (isChunkAtWordBoundary(chunk, lastChunk) && !startsWithSpace(chunk.text)
&& !endsWithSpace(lastChunk.text)) {
sb.append(' ');
}
final Float dist = chunk.distanceFromEndOf(lastChunk)/3;
for(int i = 0; i<Math.round(dist); i++) {
sb.append(' ');
}
sb.append(chunk.text);
} else {
sb.append('\n');
sb.append(chunk.text);
}
}
lastChunk = chunk;
}
return sb.toString();
}
返回带有结果文本的字符串。
* /
@Override
公共字符串getResultantText(){
return getResultantText(null);
}
private void dumpState() {
for (final TextChunk location : this.locationalResult) {
location.printDiagnostics();
System.out.println();
}
}
@Override
public void renderText(final TextRenderInfo renderInfo) {
LineSegment segment = renderInfo.getBaseline();
if (renderInfo.getRise() != 0) {
final Matrix riseOffsetTransform = new Matrix(0, -renderInfo.getRise());
segment = segment.transformBy(riseOffsetTransform);
}
final TextChunk location =
new TextChunk(renderInfo.getText(), segment.getStartPoint(), segment.getEndPoint(),
renderInfo.getSingleSpaceWidth(),renderInfo);
this.locationalResult.add(location);
}
public static class TextChunk implements Comparable<TextChunk> {
/** the text of the chunk */
private final String text;
/** the starting location of the chunk */
private final Vector startLocation;
/** the ending location of the chunk */
private final Vector endLocation;
/** unit vector in the orientation of the chunk */
private final Vector orientationVector;
/** the orientation as a scalar for quick sorting */
private final int orientationMagnitude;
private final TextRenderInfo info;
private final int distPerpendicular;
private final float distParallelStart;
private final float distParallelEnd;
/** the width of a single space character in the font of the chunk */
private final float charSpaceWidth;
public TextChunk(final String string, final Vector startLocation, final Vector endLocation,
final float charSpaceWidth,final TextRenderInfo ri) {
this.text = string;
this.startLocation = startLocation;
this.endLocation = endLocation;
this.charSpaceWidth = charSpaceWidth;
this.info = ri;
Vector oVector = endLocation.subtract(startLocation);
if (oVector.length() == 0) {
oVector = new Vector(1, 0, 0);
}
this.orientationVector = oVector.normalize();
this.orientationMagnitude =
(int) (Math.atan2(this.orientationVector.get(Vector.I2), this.orientationVector.get(Vector.I1)) * 1000);
final Vector origin = new Vector(0, 0, 1);
this.distPerpendicular = (int) startLocation.subtract(origin).cross(this.orientationVector).get(Vector.I3);
this.distParallelStart = this.orientationVector.dot(startLocation);
this.distParallelEnd = this.orientationVector.dot(endLocation);
}
public Vector getStartLocation() {
return this.startLocation;
}
public Vector getEndLocation() {
return this.endLocation;
}
public String getText() {
return this.text;
}
public float getCharSpaceWidth() {
return this.charSpaceWidth;
}
private void printDiagnostics() {
System.out.println("Text (@" + this.startLocation + " -> " + this.endLocation + "): " + this.text);
System.out.println("orientationMagnitude: " + this.orientationMagnitude);
System.out.println("distPerpendicular: " + this.distPerpendicular);
System.out.println("distParallel: " + this.distParallelStart);
}
public boolean sameLine(final TextChunk as) {
if (this.orientationMagnitude != as.orientationMagnitude) {
return false;
}
if (this.distPerpendicular != as.distPerpendicular) {
return false;
}
return true;
}
public float distanceFromEndOf(final TextChunk other) {
final float distance = this.distParallelStart - other.distParallelEnd;
return distance;
}
public float myDistanceFromEndOf(final TextChunk other) {
final float distance = this.distParallelStart - other.distParallelEnd;
return distance;
}
@Override
public int compareTo(final TextChunk rhs) {
if (this == rhs) {
return 0; // not really needed, but just in case
}
int rslt;
rslt = compareInts(this.orientationMagnitude, rhs.orientationMagnitude);
if (rslt != 0) {
return rslt;
}
rslt = compareInts(this.distPerpendicular, rhs.distPerpendicular);
if (rslt != 0) {
return rslt;
}
return Float.compare(this.distParallelStart, rhs.distParallelStart);
}
private static int compareInts(final int int1, final int int2) {
return int1 == int2 ? 0 : int1 < int2 ? -1 : 1;
}
public TextRenderInfo getInfo() {
return this.info;
}
}
@Override
public void renderImage(final ImageRenderInfo renderInfo) {
// do nothing
}
public static interface TextChunkFilter {
public boolean accept(TextChunk textChunk);
}
}
如您所见,大多数与原始类相同。我刚刚添加了这个:
final Float dist = chunk.distanceFromEndOf(lastChunk)/3;
for(int i = 0; i<Math.round(dist); i++) {
sb.append(' ');
}
到getResultantText方法以扩展带有空格的间隙。
但这是问题所在:
距离似乎不准确或不准确。结果看起来像
这个:
有谁知道如何计算距离的更好值?我认为这是因为原始字体类型是ArialMT,而我的编辑器则处于快递状态,但是要使用此工作表,建议我可以将表拆分到正确的位置以获取数据。由于值usw的浮动开始和结束,因此很难。
:-/
最佳答案
您的方法插入这样的空间的问题
final Float dist = chunk.distanceFromEndOf(lastChunk)/3;
for(int i = 0; i<Math.round(dist); i++) {
sb.append(' ');
}
假定字符宽度宽度为3个用户空间单位,则假定
StringBuffer
中的当前位置与lastChunk
的末尾完全对应。不必如此,通常每次添加字符都会破坏这种以前的对应关系。例如。当使用比例字体时,这两行的宽度不同:伊莉莉莉
MWMWMWM
而在
StringBuffer
中,它们占据相同的长度。因此,您必须查看
chunk
相对于左页面边框的起始位置,并在缓冲区中相应添加空格。此外,您的代码在行的开头完全忽略了可用空间。
如果用以下代码代替原始方法
getResultantText(TextChunkFilter
,则结果应会得到改善:public String getResultantText(TextChunkFilter chunkFilter){
if (DUMP_STATE) dumpState();
List<TextChunk> filteredTextChunks = filterTextChunks(locationalResult, chunkFilter);
Collections.sort(filteredTextChunks);
int startOfLinePosition = 0;
StringBuffer sb = new StringBuffer();
TextChunk lastChunk = null;
for (TextChunk chunk : filteredTextChunks) {
if (lastChunk == null){
insertSpaces(sb, startOfLinePosition, chunk.distParallelStart, false);
sb.append(chunk.text);
} else {
if (chunk.sameLine(lastChunk))
{
if (isChunkAtWordBoundary(chunk, lastChunk))
{
insertSpaces(sb, startOfLinePosition, chunk.distParallelStart, !startsWithSpace(chunk.text) && !endsWithSpace(lastChunk.text));
}
sb.append(chunk.text);
} else {
sb.append('\n');
startOfLinePosition = sb.length();
insertSpaces(sb, startOfLinePosition, chunk.distParallelStart, false);
sb.append(chunk.text);
}
}
lastChunk = chunk;
}
return sb.toString();
}
void insertSpaces(StringBuffer sb, int startOfLinePosition, float chunkStart, boolean spaceRequired)
{
int indexNow = sb.length() - startOfLinePosition;
int indexToBe = (int)((chunkStart - pageLeft) / fixedCharWidth);
int spacesToInsert = indexToBe - indexNow;
if (spacesToInsert < 1 && spaceRequired)
spacesToInsert = 1;
for (; spacesToInsert > 0; spacesToInsert--)
{
sb.append(' ');
}
}
public float pageLeft = 0;
public float fixedCharWidth = 6;
pageLeft
是左页面边框的坐标。该策略不知道,因此必须明确告知;但是,在许多情况下,0是正确的值。或者,可以使用所有块的最小
distParallelStart
值。这将切断左边距,但不需要您注入确切的左侧页面边框值。fixedCharWidth
是假定的字符宽度。根据所讨论的PDF中的文字,不同的值可能更合适。在您的情况下,值3似乎比我的6好。此代码仍有很多改进空间。例如。
假定没有文本块跨越多个表列。这种假设通常是正确的,但我看到了奇怪的PDF,其中正常的字间间距是通过使用单独的文本块以一定的偏移量实现的,但列间的间距由单个块中的单个空格字符表示(跨一列的末尾和下一列的开始)!该空格字符的宽度已通过PDF图形状态的字间距设置进行了控制。
它忽略了不同数量的垂直空间。
关于java - iText阅读PDF一样pdftotext -layout吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24887784/