Extract text from a rect-like 'cell' as plain or MD styled text. This function should ultimately be used to extract text from a table cell. Markdown output will only work correctly if extraction flag bit TEXT_COLLECT_STYLES is set. Args: textpage: A PyMuPDF TextPage object.
(textpage, cell, markdown=False)
| 221 | |
| 222 | |
| 223 | def extract_cells(textpage, cell, markdown=False): |
| 224 | """Extract text from a rect-like 'cell' as plain or MD styled text. |
| 225 | |
| 226 | This function should ultimately be used to extract text from a table cell. |
| 227 | Markdown output will only work correctly if extraction flag bit |
| 228 | TEXT_COLLECT_STYLES is set. |
| 229 | |
| 230 | Args: |
| 231 | textpage: A PyMuPDF TextPage object. Must have been created with |
| 232 | TEXTFLAGS_TEXT | TEXT_COLLECT_STYLES. |
| 233 | cell: A tuple (x0, y0, x1, y1) defining the cell's bbox. |
| 234 | markdown: If True, return text formatted for Markdown. |
| 235 | |
| 236 | Returns: |
| 237 | A string with the text extracted from the cell. |
| 238 | """ |
| 239 | text = "" |
| 240 | for block in textpage.extractRAWDICT()["blocks"]: |
| 241 | if block["type"] != 0: |
| 242 | continue |
| 243 | block_bbox = block["bbox"] |
| 244 | if ( |
| 245 | 0 |
| 246 | or block_bbox[0] > cell[2] |
| 247 | or block_bbox[2] < cell[0] |
| 248 | or block_bbox[1] > cell[3] |
| 249 | or block_bbox[3] < cell[1] |
| 250 | ): |
| 251 | continue # skip block outside cell |
| 252 | for line in block["lines"]: |
| 253 | lbbox = line["bbox"] |
| 254 | if ( |
| 255 | 0 |
| 256 | or lbbox[0] > cell[2] |
| 257 | or lbbox[2] < cell[0] |
| 258 | or lbbox[1] > cell[3] |
| 259 | or lbbox[3] < cell[1] |
| 260 | ): |
| 261 | continue # skip line outside cell |
| 262 | |
| 263 | if text: # must be a new line in the cell |
| 264 | text += "<br>" if markdown else "\n" |
| 265 | |
| 266 | # strikeout detection only works with horizontal text |
| 267 | horizontal = line["dir"] == (0, 1) or line["dir"] == (1, 0) |
| 268 | |
| 269 | for span in line["spans"]: |
| 270 | sbbox = span["bbox"] |
| 271 | if ( |
| 272 | 0 |
| 273 | or sbbox[0] > cell[2] |
| 274 | or sbbox[2] < cell[0] |
| 275 | or sbbox[1] > cell[3] |
| 276 | or sbbox[3] < cell[1] |
| 277 | ): |
| 278 | continue # skip spans outside cell |
| 279 | |
| 280 | # only include chars with more than 50% bbox overlap |
no test coverage detected
searching dependent graphs…