Is it possible to perform an OCR in certain area in a PDF with python? I am trying to build a program to extract some information from every PDF sheet like what Autodesk BIM360 do
-
1The answer to "Is it possible to..." is yes as long as it's not self-inconsistent. How to Ask– JulienMay 26 at 8:09
1 Answer
disclaimer: I am the author of borb
(the library used in this answer)
borb
is an open-source, pure Python PDF library that plays nice with other famous libraries. e.g. you can insert PIL
images, or matplotlib
charts, and you can use pytesseract
to apply OCR to your document.
There is a large examples repository in case you want to learn more. You can find a working example of OCR there as well.
I'll repeat the example here for completeness:
#!chapter_007/src/snippet_005.py
def main():
# set up everything for OCR
tesseract_data_dir: Path = Path("/home/joris/Downloads/tessdata-master/")
assert tesseract_data_dir.exists()
l: OCRAsOptionalContentGroup = OCRAsOptionalContentGroup(tesseract_data_dir)
# read Document
doc: typing.Optional[Document] = None
with open("output_001.pdf", "rb") as pdf_file_handle:
doc = PDF.loads(pdf_file_handle, [l])
assert doc is not None
# store Document
with open("output_002.pdf", "wb") as pdf_file_handle:
PDF.dumps(pdf_file_handle, doc)
if __name__ == "__main__":
main()
What's happening here is that the OCR process is dumping its results in an invisible layer of the PDF (these are called optional content groups). Hence the name OCRAsOptionalContentGroup
.
Afterwards, you can store the Document
again, and it will appear to contain text, youll be able to search it, select the text, and everything you
re used to.