使用PDFMiner for Python将pdf的所有页面合并为一个文本

时间:2019-03-09 10:12:15

标签: python pdfminer

我正在尝试将PDF文件的所有页面合并为一个文本,然后将此文本保存为JSON文件。

我没问题,但是它仅从PDF文件的第一页中提取文本。

如何遍历PDF文件并将文本附加到JSON文件?谢谢您的提示。

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
import io
from io import StringIO
from io import BytesIO
import os
import glob
import json

pdf_path = 'pdfs' 
pdfFiles = [os.path.join(pdf_path, f) for f in os.listdir(pdf_path) if f.endswith(".pdf") if os.path.isfile(os.path.join(pdf_path, f))]

extractTextFromPdf(pdfFiles[0])

def extractTextFromPdfByPage(pdf_path):
 with open(pdf_path, 'rb') as fh:
    resourceManager = PDFResourceManager()
    returnString = StringIO()
    codec = 'utf-8'
    laParams = LAParams()
    device = TextConverter(resourceManager, returnString, codec=codec, laparams=laParams)

    filename = os.path.splitext(os.path.basename(pdf_path))[0]

    for page in PDFPage.get_pages(fh, 
                                  caching=True,
                                  check_extractable=True):
        resource_manager = PDFResourceManager()
        fake_file_handle = io.StringIO()
        converter = TextConverter(resource_manager, fake_file_handle)
        page_interpreter = PDFPageInterpreter(resource_manager, converter)
        page_interpreter.process_page(page)

        text = fake_file_handle.getvalue()
        yield text

        converter.close()
        fake_file_handle.close()

        data = {'id': filename, 'text': text}

        json_path = 'stage0.json'

        with open(json_path, 'w') as fh:
            json.dump(data, fh)

        return text

    device.close()
    returnString.close()

def extractTextFromPdf(pdf_path):
    for page in extractTextFromPdfByPage(pdf_path):
        print(page)
        print()

0 个答案:

没有答案