python pdf转txt文本、pdf转json

文章目录


一、前言

此方法只能转文本格式的pdf,如果是图片格式的pdf需要用到ocr包,以后如果有这方面需求再加这个方法


二、实现方法

1. 目录结构


2. 代码

pdf2txt.py 代码如下

python 复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams


def batch_process(src_dir, tgt_dir):
    '''
    批处理
    :return:
    '''
    for pdf_name in os.listdir(src_dir):
        pdf_path = os.path.join(src_dir, pdf_name)
        text_path = os.path.join(tgt_dir, f'{os.path.splitext(pdf_name)[0]}.txt')
        json_path = os.path.join(tgt_dir, f'{os.path.splitext(pdf_name)[0]}.json')

        pdf_utils = PDFUtils()
        pdf_list = pdf_utils.pdf2list(pdf_path)

        # pdf2txt
        with open(text_path, mode='w', encoding='utf-8') as f:
            f.write(''.join([''.join(page) for page in pdf_list]))

        # pdf2json
        with open(json_path, mode='w', encoding='utf-8') as f:
            f.write(json.dumps(pdf_list, ensure_ascii=False))


class PDFUtils():

    def __init__(self):
        pass

    def pdf2list(self, path):

        pdf_list = []   # 二维数组,一维放页,二维放行
        with open(path, 'rb') as f:
            praser = PDFParser(f)

            doc = PDFDocument(praser)

            if not doc.is_extractable:
                raise PDFTextExtractionNotAllowed

            pdfrm = PDFResourceManager()

            laparams = LAParams()

            device = PDFPageAggregator(pdfrm, laparams=laparams)

            interpreter = PDFPageInterpreter(pdfrm, device)

            for page_idx, page in enumerate(PDFPage.create_pages(doc)):

                line_list = []   # 保存每行数据
                # print(page_idx)
                interpreter.process_page(page)
                layout = device.get_result()
                for line_idx, line in enumerate(layout):
                    # print(line_idx)
                    if hasattr(line, "get_text"):
                        content = line.get_text()
                        # print(content)
                        # output = StringIO()
                        # output.write(content)
                        # content = output.getvalue()
                        # output.close()
                        # print(content)
                        if content and content.replace(' ', '') != '\n':
                            line_list.append(content)
                            # print(content)


                pdf_list.append(line_list)

        # output.close()
        return pdf_list


if __name__ == '__main__':
	
	# pdf目录
    src_dir = './pdf'
    # 生成的txt和json文件的保存目录
    tgt_dir = './text_and_json'
    
    # 批量转换
    batch_process(src_dir, tgt_dir)
相关推荐
0思必得024 分钟前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
2301_8223827642 分钟前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
喵手1 小时前
Python爬虫实战:从零搭建字体库爬虫 - requests+lxml 实战采集字体网字体信息数据(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·采集字体库数据·字体库字体信息采集
2301_790300962 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
程序员敲代码吗3 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
Yyyyy123jsjs3 小时前
如何通过免费的外汇API轻松获取实时汇率数据
开发语言·python
喵手3 小时前
Python爬虫实战:GovDataMiner —— 开放数据门户数据集元数据采集器(附 CSV 导出)!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·open data·开放数据门户数据集列表
历程里程碑3 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
人工智能AI技术4 小时前
【Agent从入门到实践】43 接口封装:将Agent封装为API服务,供其他系统调用
人工智能·python