OCRMyPDF在win10+python3.6中被调用
OCRmyPDF是基于Tesseract和python3的应用程序,它可以将不可复制粘贴的PDF文件转换为可以复制粘贴的PDF文件。OCRmyPDF的部分功能可以在python中调用,本文将介绍如何在win10+python3.6中调用OCRmyPDF。
OCRmyPDF安装
请参考Installing on Windows。如下图所示,OCRmyPDF要求Python 3.7+/Tesseract 4.0+/Ghostscript 9.50+。
我电脑中安装的是Tesseract5和Python3.6,亲测可正常使用。Python和Tesseract的安装攻略有很多,大家可自行查找。
下面总结在Python3.6和Tesseract5已安装的前提下,OCRmyPDF的安装步骤。
1. 根据需求下载Ghostscript并安装。
2. 打开Command.exe,安装ghostscript。注意:这里通过[pip install ghostscript]安装的ghostscript是基于ctypes的Ghostscript C-API的接口,该接口需要第1步的安装才能正常工作。
1 |
pip install ghostscript |
3. 打开Command.exe,安装OCRmyPDF
1 |
pip install ocrmypdf |
4. 安装完成后,在命令行输入
1 |
ocrmypdf --help |
出现如下内容说明安装成功。
1 |
C:\Users\cheng>ocrmypdf --help usage: ocrmypdf [-h] [-l LANGUAGES] [--image-dpi DPI] [--output-type {pdfa,pdf,pdfa-1,pdfa-2,pdfa-3}] [--sidecar [FILE]] [--version] [-j N] [-q] [-v [VERBOSE]] [--title TITLE] [--author AUTHOR] [--subject SUBJECT] [--keywords KEYWORDS] [-r] [--remove-background] [-d] [-c] [-i] [--unpaper-args UNPAPER_ARGS] [--oversample DPI] [--remove-vectors] [--threshold] [-f] [-s] [--redo-ocr] [--skip-big MPixels] [-O {0,1,2,3}] [--jpeg-quality Q] [--png-quality Q] [--jbig2-lossy] [--pages PAGES] [--max-image-mpixels MPixels] [--pdf-renderer {auto,hocr,sandwich,hocrdebug}] [--rotate-pages-threshold CONFIDENCE] [--pdfa-image-compression {auto,jpeg,lossless}] [--fast-web-view MEGABYTES] [--plugin PLUGINS] [-k] [--tesseract-config CFG] [--tesseract-pagesegmode PSM] [--tesseract-oem MODE] [--tesseract-timeout SECONDS] [--user-words FILE] [--user-patterns FILE] input_pdf_or_image output_pdf |
在python中调用OCRmyPDF
参考Using the OCRmyPDF API, 新建一个testOCRMyPDF.py文件,输入以下代码:
1 2 3 |
import ocrmypdf if__name__ == '__main__':# To ensure correct behavior on Windows and macOS ocrmypdf.ocr('input.pdf', 'output.pdf', deskew=True) |
将待处理的pdf文件input.pdf拷贝到与testOCRMyPDF.py相同路径下,运行testOCRMyPDF.py,运行界面如下:
1 2 3 4 5 |
Scanning contents: 100%|███████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 8.63page/s] OCR: 50%|████████████████████████████████████▌ OCR: 100%|█████████████████████████████████████████████████████████████████████████| 1.0/1.0 [00:03<00:00, 3.44s/page] PDF/A conversion: 100%|████████████████████████████████████████████████ ████████████████| 1/1 [00:00<00:00, 5.60page/s] JPEGs: 0image [00:00, ?image/s] JBIG2: 0item [00:00, ?item/s] |
输入的input.pdf是不可以复制其中的文字,但经过OCRMyPDF处理之后的output.pdf的内容与input.pdf的内容完全一致而且可以复制其中的内容。