更多代码在 Github
使用 ocrmypdf ,根据官方教程安装。Linux系统(包含MacOS,WSL)会简单一点,Windows复杂一点。
使用方法:直接在命令行执行
ocrmypdf --pages 1 --optimize 0 --output-type none --sidecar output.txt input.pdf -
–pages 1 是仅处理 pdf 的第一页,–optimize 0 禁用页面优化,–output-type none是不输出额外的一个pdf(需要配合最后的 -)
还可以加上 --quiet 不让打印过程
会在本地保存一个 output.txt 里面存有识别的文字。
默认的是英文,可以替换为其他语言
如果想要写入python,注意如果简单加进去会报一个错误 python stdout is connected to a terminal. Please redirect stdout to a file.
下面的程序中已经修复了。
import os
import subprocess
import shlex
file = 'test.pdf'
command = f"ocrmypdf --deskew --rotate-pages --rotate-pages-threshold 5 --output-type none --sidecar ocr_output.txt {file} -"
command_args = shlex.split(command)
with open('log', "w") as outfile:
subprocess.run(command_args, stdout=outfile)
os.remove('log')