You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测并修正180°倒置PDF文件以实现文本识别?

识别并修正180°倒置的PDF文件

核心逻辑

通过OCR检测PDF页面文本的旋转角度,判定是否为180°倒置,再对页面反向旋转修正,最终生成可读PDF。

所需工具

  • Python库:PyPDF2(处理PDF页面旋转)、pdf2image(PDF转图片)、pytesseract(调用Tesseract OCR检测文本方向)
  • Tesseract OCR引擎:需提前安装并配置环境变量(Windows从GitHub下载安装包,Linux用apt install tesseract-ocr,macOS用brew install tesseract)

实现步骤

1. 安装依赖

执行以下命令安装Python库:

pip install PyPDF2 pdf2image pytesseract

2. 检测页面旋转角度

将PDF页面转为图片后,用Tesseract提取文本旋转角度:

from pdf2image import convert_from_path
import pytesseract

def detect_rotation_angle(pdf_path, page_num=0):
    # 转换指定PDF页面为图片
    pages = convert_from_path(pdf_path, first_page=page_num+1, last_page=page_num+1)
    img = pages[0]
    # 调用Tesseract检测文本方向
    osd_result = pytesseract.image_to_osd(img)
    # 解析旋转角度
    angle = int(osd_result.split('Rotate: ')[1].split('\n')[0])
    return angle

3. 修正倒置页面并生成新PDF

根据检测角度旋转页面,保存修正后的PDF:

from PyPDF2 import PdfReader, PdfWriter

def fix_inverted_pdf(input_pdf_path, output_pdf_path):
    reader = PdfReader(input_pdf_path)
    writer = PdfWriter()
    
    for page_num in range(len(reader.pages)):
        page = reader.pages[page_num]
        angle = detect_rotation_angle(input_pdf_path, page_num)
        # 180°倒置则旋转修正
        if angle == 180:
            page.rotate(180)
        writer.add_page(page)
    
    with open(output_pdf_path, 'wb') as out_file:
        writer.write(out_file)

4. 批量处理多份PDF

遍历指定目录,批量修正所有PDF:

import os

def batch_fix_pdfs(input_dir, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    for filename in os.listdir(input_dir):
        if filename.endswith('.pdf'):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, f"fixed_{filename}")
            fix_inverted_pdf(input_path, output_path)
            print(f"已完成修正:{output_path}")

注意事项

  • 加密PDF需先解密再处理
  • 低分辨率或模糊页面可能影响OCR角度检测精度
  • 表格类PDF修正后不会破坏原有结构,仅调整页面方向

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 13:26:02