1 31 package org.pdfbox.util; 32 33 import java.util.Comparator ; 34 35 import org.pdfbox.pdmodel.PDPage; 36 37 43 public class TextPositionComparator implements Comparator 44 { 45 private PDPage thePage = null; 46 47 52 public TextPositionComparator( PDPage page ) 53 { 54 thePage = page; 55 } 56 57 60 public int compare(Object o1, Object o2) 61 { 62 int retval = 0; 63 TextPosition pos1 = (TextPosition)o1; 64 TextPosition pos2 = (TextPosition)o2; 65 int rotation = thePage.findRotation(); 66 float x1 = 0; 67 float x2 = 0; 68 float pos1YBottom = 0; 69 float pos2YBottom = 0; 70 if( rotation == 0 ) 71 { 72 x1 = pos1.getX(); 73 x2 = pos2.getX(); 74 pos1YBottom = pos1.getY(); 75 pos2YBottom = pos2.getY(); 76 } 77 else if( rotation == 90 ) 78 { 79 x1 = pos1.getY(); 80 x2 = pos2.getX(); 81 pos1YBottom = pos1.getX(); 82 pos2YBottom = pos2.getY(); 83 } 84 else if( rotation == 180 ) 85 { 86 x1 = -pos1.getX(); 87 x2 = -pos2.getX(); 88 pos1YBottom = -pos1.getY(); 89 pos2YBottom = -pos2.getY(); 90 } 91 else if( rotation == 270 ) 92 { 93 x1 = -pos1.getY(); 94 x2 = -pos2.getY(); 95 pos1YBottom = -pos1.getX(); 96 pos2YBottom = -pos2.getX(); 97 } 98 float pos1YTop = pos1YBottom - pos1.getHeight(); 99 float pos2YTop = pos2YBottom - pos2.getHeight(); 100 101 float yDifference = Math.abs( pos1YBottom-pos2YBottom); 102 if( yDifference < .1 || 104 (pos2YBottom >= pos1YTop && pos2YBottom <= pos1YBottom) || 105 (pos1YBottom >= pos2YTop && pos1YBottom <= pos2YBottom)) 106 { 107 if( x1 < x2 ) 108 { 109 retval = -1; 110 } 111 else if( x1 > x2 ) 112 { 113 retval = 1; 114 } 115 else 116 { 117 retval = 0; 118 } 119 } 120 else if( pos1YBottom < pos2YBottom ) 121 { 122 retval = -1; 123 } 124 else 125 { 126 return 1; 127 } 128 129 return retval; 130 } 131 132 } | Popular Tags |