Extract plain text avoiding unacceptable line breaks. Text contained in clip will be sorted in reading sequence. Some effort is also spent to simulate layout vertically and horizontally. Args: page: pymupdf.Page clip: (rect-like) only consider text inside flags:
(
page: pymupdf.Page,
clip: rect_like = None,
flags: OptInt = None,
textpage: pymupdf.TextPage = None,
tolerance=3,
)
| 163 | |
| 164 | |
| 165 | def get_sorted_text( |
| 166 | page: pymupdf.Page, |
| 167 | clip: rect_like = None, |
| 168 | flags: OptInt = None, |
| 169 | textpage: pymupdf.TextPage = None, |
| 170 | tolerance=3, |
| 171 | ) -> str: |
| 172 | """Extract plain text avoiding unacceptable line breaks. |
| 173 | |
| 174 | Text contained in clip will be sorted in reading sequence. Some effort |
| 175 | is also spent to simulate layout vertically and horizontally. |
| 176 | |
| 177 | Args: |
| 178 | page: pymupdf.Page |
| 179 | clip: (rect-like) only consider text inside |
| 180 | flags: (int) text extraction flags |
| 181 | textpage: pymupdf.TextPage |
| 182 | tolerance: (float) consider words to be on the same line if their top |
| 183 | or bottom coordinates do not differ more than this. |
| 184 | |
| 185 | Notes: |
| 186 | If a TextPage is provided, all text is checked for being inside clip |
| 187 | with at least 50% of its bbox. |
| 188 | This allows to use some "global" TextPage in conjunction with sub- |
| 189 | selecting words in parts of the defined TextPage rectangle. |
| 190 | |
| 191 | Returns: |
| 192 | A text string in reading sequence. Left indentation of each line, |
| 193 | inter-line and inter-word distances strive to reflect the layout. |
| 194 | """ |
| 195 | |
| 196 | def line_text(clip, line): |
| 197 | """Create the string of one text line. |
| 198 | |
| 199 | We are trying to simulate some horizontal layout here, too. |
| 200 | |
| 201 | Args: |
| 202 | clip: (pymupdf.Rect) the area from which all text is being read. |
| 203 | line: (list) word tuples (rect, text) contained in the line |
| 204 | Returns: |
| 205 | Text in this line. Generated from words in 'line'. Distance from |
| 206 | predecessor is translated to multiple spaces, thus simulating |
| 207 | text indentations and large horizontal distances. |
| 208 | """ |
| 209 | line.sort(key=lambda w: w[0].x0) |
| 210 | ltext = "" # text in the line |
| 211 | x1 = clip.x0 # end coordinate of ltext |
| 212 | lrect = pymupdf.EMPTY_RECT() # bbox of this line |
| 213 | for r, t in line: |
| 214 | lrect |= r # update line bbox |
| 215 | # convert distance to previous word to multiple spaces |
| 216 | dist = max( |
| 217 | int(round((r.x0 - x1) / r.width * len(t))), |
| 218 | 0 if (x1 == clip.x0 or r.x0 <= x1) else 1, |
| 219 | ) # number of space characters |
| 220 | |
| 221 | ltext += " " * dist + t # append word string |
| 222 | x1 = r.x1 # update new end position |
no test coverage detected
searching dependent graphs…