hOCR output from OCRmyPDF

Viewed 178

I'm running OCRmyPDF to create searchable PDFs from scanned PDFs, and it is working very fine for me. I just want to save the hOCR output as well in my local directory for every page of the scanned PDF. How can I do that?

1 Answers

I was able to do that by adding a plugin:

from os.path import splitext
import shutil

from ocrmypdf import hookimpl
from ocrmypdf.builtin_plugins.tesseract_ocr import TesseractOcrEngine


class TesseractHocrEngine(TesseractOcrEngine):
    @staticmethod
    def generate_hocr(input_file, output_hocr, output_text, options):
        TesseractOcrEngine.generate_hocr(input_file, output_hocr, output_text, options)

        output_file = options.output_file
        if not output_file:
            return

        output_file_name, _ = splitext(output_file)
        output_file_hocr = output_file_name + ".hocr"
        shutil.copyfile(output_hocr, output_file_hocr)


@hookimpl
def get_ocr_engine():
    return TesseractHocrEngine()

Then add it to the opts:

opts["plugins"] = os.path.join(current_folder, "tesseract_hocr_plugin.py")
exit_code = ocrmypdf.ocr(in_path, out_path, **opts)

Just be wary that OCRmyPDF does not always generate an hOCR file.

Related