簡體   English   中英

創建可搜索(多頁)PDF 和 Python

[英]Create searchable (multipage) PDF with Python

我在網上找到了一些關於如何使 PDF 被掃描后可搜索的指南。 但是,我目前正在努力弄清楚如何為多頁 PDF 執行此操作。

我的代碼采用多頁 PDF,將每一頁轉換為 JPG,在每一頁上運行 OCR,然后將其轉換為 PDF。但是,僅返回最后一頁。

import pytesseract
from pdf2image import convert_from_path

pytesseract.pytesseract.tesseract_cmd = 'directory'
TESSDATA_PREFIX = 'directory'
tessdata_dir_config = '--tessdata-dir directory'

# Path of the pdf
PDF_file = r"pdf directory"
  
  
def pdf_text():
    
    # Store all the pages of the PDF in a variable
    pages = convert_from_path(PDF_file, 500)
  
    image_counter = 1

    for page in pages:

        # Declare file names
        filename = "page_"+str(image_counter)+".jpg"

        # Save the image of the page in system
        page.save(filename, 'JPEG')

        # Increment the counter to update filename
        image_counter = image_counter + 1

    # Variable to get count of total number of pages
    filelimit = image_counter-1

    outfile = "out_text.pdf"

    # Open the file in append mode so that all contents of all images are added to the same file
    
    f = open(outfile, "a")

    # Iterate from 1 to total number of pages
    for i in range(1, filelimit + 1):

        filename = "page_"+str(i)+".jpg"

        # Recognize the text as string in image using pytesseract
        result =  pytesseract.image_to_pdf_or_hocr(filename, lang="eng", config=tessdata_dir_config) 

            
        f = open(outfile, "w+b")
        f.write(bytearray(result))
        f.close()

pdf_text()

我怎樣才能對所有頁面和 output 一個合並的 PDF 運行這個?

我無法運行它,但我認為所有問題都是因為您在循環內使用open(..., 'w+b') - 這會刪除以前的內容,最后您只寫最后一頁。

您應該使用已經打開的文件open(outfile, "a")並在循環后關閉它。

# --- before loop ---

f = open(outfile, "ab")

# --- loop ---

for i in range(1, filelimit+1):

    filename = f"page_{i}.jpg"

    result =  pytesseract.image_to_pdf_or_hocr(filename, lang="eng", config=tessdata_dir_config) 

    f.write(bytearray(result))

# --- after loop ---
        
f.close()

順便提一句:

但還有其他問題 - image_to_pdf_or_hocr創建完整PDF - 帶有特殊的頁眉和頁腳 - 並且附加兩個結果無法創建正確PDF 您將不得不使用特殊模塊來合並 pdf。 點贊合並 PDF 個文件

類似於

    # --- before loop ---
    
    from PyPDF2 import PdfFileMerger
    import io

    merger = PdfFileMerger()

    # --- loop ---
    
    for i in range(1, filelimit + 1):

        filename = "page_"+str(i)+".jpg"

        result =  pytesseract.image_to_pdf_or_hocr(filename, lang="eng", config=tessdata_dir_config)
        
        pdf_file_in_memory = io.BytesIO(result)        
        merger.append(pdf_file_in_memory)
        
    # --- after loop ---
    
    merger.write(outfile)
    merger.close()

這里有許多潛在的問題,如果無法調試,很難說出根本原因是什么。

JPG 是否已成功創建,並且是否如預期的那樣作為單獨的文件?

我懷疑pages = convert_from_path(PDF_file, 500)沒有按預期返回 - 您是否手動驗證它們是否按預期創建?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM