Return a PDF string depending on its coding. Notes: Returns a string bracketed with either "()" or "<>" for hex values. If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else
(s: str)
| 22297 | |
| 22298 | |
| 22299 | def get_pdf_str(s: str) -> str: |
| 22300 | """ Return a PDF string depending on its coding. |
| 22301 | |
| 22302 | Notes: |
| 22303 | Returns a string bracketed with either "()" or "<>" for hex values. |
| 22304 | If only ascii then "(original)" is returned, else if only 8 bit chars |
| 22305 | then "(original)" with interspersed octal strings \nnn is returned, |
| 22306 | else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the |
| 22307 | UTF-16BE encoding of the original. |
| 22308 | """ |
| 22309 | if not bool(s): |
| 22310 | return "()" |
| 22311 | |
| 22312 | def make_utf16be(s): |
| 22313 | r = bytearray([254, 255]) + bytearray(s, "UTF-16BE") |
| 22314 | return "<" + r.hex() + ">" # brackets indicate hex |
| 22315 | |
| 22316 | # The following either returns the original string with mixed-in |
| 22317 | # octal numbers \nnn for chars outside the ASCII range, or returns |
| 22318 | # the UTF-16BE BOM version of the string. |
| 22319 | r = "" |
| 22320 | for c in s: |
| 22321 | oc = ord(c) |
| 22322 | if oc > 255: # shortcut if beyond 8-bit code range |
| 22323 | return make_utf16be(s) |
| 22324 | |
| 22325 | if oc > 31 and oc < 127: # in ASCII range |
| 22326 | if c in ("(", ")", "\\"): # these need to be escaped |
| 22327 | r += "\\" |
| 22328 | r += c |
| 22329 | continue |
| 22330 | |
| 22331 | if oc > 127: # beyond ASCII |
| 22332 | r += f"\\{oc:03o}" |
| 22333 | continue |
| 22334 | |
| 22335 | # now the white spaces |
| 22336 | if oc == 8: # backspace |
| 22337 | r += "\\b" |
| 22338 | elif oc == 9: # tab |
| 22339 | r += "\\t" |
| 22340 | elif oc == 10: # line feed |
| 22341 | r += "\\n" |
| 22342 | elif oc == 12: # form feed |
| 22343 | r += "\\f" |
| 22344 | elif oc == 13: # carriage return |
| 22345 | r += "\\r" |
| 22346 | else: |
| 22347 | r += "\\267" # unsupported: replace by 0xB7 |
| 22348 | |
| 22349 | return "(" + r + ")" |
| 22350 | |
| 22351 | |
| 22352 | def get_tessdata(tessdata=None): |
no test coverage detected
searching dependent graphs…