OfficeAutomation——Task04 Python 操作 PDF

本文档介绍了如何使用Python的PyPDF2和pdfplumber库进行PDF文件的操作,包括批量拆分、合并、提取文字、表格和图片内容。此外,还涉及到将PDF转换为图片、添加水印、文档加密解密等。通过示例代码展示了如何读取PDF内容,并使用jieba进行关键词提取,最后给出了创建PDF文件的示例。
摘要由CSDN通过智能技术生成

OfficeAutomation——Task04 Python 操作 PDF

links:
https://github.com/datawhalechina/team-learning-program/blob/master/OfficeAutomation/Task04%20Python%E6%93%8D%E4%BD%9CPDF.md

  1. 批量拆分
  2. 批量合并
  3. 提取文字内容
  4. 提取表格内容
  5. 提取图片内容
  6. 转换为图片
    7.1 安装 pdf2image
    7.2 安装组件
  7. 添加水印
  8. 文档加密与解密

Python 操作 PDF 会用到两个库,分别是:PyPDF2 和 pdfplumber
其中 PyPDF2 可以更好的读取、写入、分割、合并PDF文件,而 pdfplumber 可以更好的读取 PDF 文
件中内容和提取 PDF 中的表格
对应的官网分别是:
PyPDF2:https://pythonhosted.org/PyPDF2/
pdfplumber:https://github.com/jsvine/pdfplumber

读取pdf文档中的内容:

import sys
import importlib
importlib.reload(sys)
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
import jieba
'''解析pdf 文本,保存到txt文件中'''
def parse(path):
    # 以二进制读模式打开
    fp = open(path, 'rb')
    #用文件对象来创建一个pdf文档分析器
    praser = PDFParser(fp)
    # 创建一个PDF文档
    doc = PDFDocument()
    # 连接分析器 与文档对象
    praser.set_document(doc)
    doc.set_parser(praser)
    # 提供初始化密码
    # 如果没有密码 就创建一个空的字符串
    doc.initialize()
    # 检测文档是否提供txt转换,不提供就忽略
    if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        # 创建PDf 资源管理器 来管理共享资源
        rsrcmgr = PDFResourceManager()
        # 创建一个PDF设备对象
        laparams = LAParams()
        device = PDFPageAggregator(rsrcmgr, laparams=laparams)
        # 创建一个PDF解释器对象
        interpreter = PDFPageInterpreter(rsrcmgr, device)
        # 循环遍历列表,每次处理一个page的内容
        # doc.get_pages() 获取page列表
        results=''
        for page in doc.get_pages():
            interpreter.process_page(page)
            # 接受该页面的LTPage对象
            layout = device.get_result()
            # 这里layout是一个LTPage对象,里面存放着这个page解析出的各种对象
            # 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal
            # 等等,想要获取文本就获得对象的text属性,
            for x in layout:
                if (isinstance(x, LTTextBoxHorizontal)):
                    result = x.get_text()
                    results = results+result
        return results
# 实现关键字的提取:
def extract(page, exclude):
    # 使用jieba进行分词,将文本分成词语列表
    words = jieba.lcut(page)
    print(words)
    count = {}
    # 使用 for 循环遍历每个词语并统计个数
    for word in words:
        # 排除单个字的干扰,使得输出结果为词语
        if len(word) < 2:
            continue
        else:
            # 如果字典里键为word的值存在,则返回键的值并加一,
            # 如果不存在键word,则返回0再加上1
            count[word] = count.get(word, 0) + 1
    # 遍历字典的所有键,即所有word
    key_list = []
    for key in count.keys():
        key_list.append(key)
    for key in key_list:
        if key in exclude:
            # 删除字典中键为无关词语的键值对
            del count[key]
    # 将字典的所有键值对转化为列表
    items_list = []
    for item in count.items():
        items_list.append(item)
    # 对列表按照词频从大到小的顺序排序
    items_list.sort(key=lambda x: x[1], reverse=True)
    # 此处统计排名前五的单词,所以range(5)
    list_result = []
    for i in range(5):
        word, number = items_list[i]
        result = "关键词:"+word+":"+str(number)
        list_result.append(result)
    return list_result
if __name__ == '__main__':
    # 把你需要分析的文件路径放在下面的list中:
    paths = ['/Users/.pdf',]
    for path in paths:
        page_result = parse(path)
        # 建立无关词语列表:即关键词中不需要呈现的词
        excludes = ["可以", "一起", "这样"]
        keyword = extract(page_result, excludes)
        print(keyword)


pdf文件的生成:

from reportlab.pdfgen import canvas
from reportlab.platypus.tables import Table, TableStyle
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph,Frame
from reportlab.lib.pagesizes import letter, A4
from reportlab.platypus import Image as platImage
from PIL import Image
from reportlab.lib import colors
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
#支持中文,需要下载相应的文泉驿中文字体
pdfmetrics.registerFont(TTFont('hei', 'hei.TTF'))
import testSubFun
testSubFun.testSubFunc('first')
#设置页面大小
c = canvas.Canvas('测试.pdf',pagesize=A4)
xlength,ylength = A4
print('width:%d high:%d'%(xlength,ylength))
#c.line(1,1,ylength/2,ylength)
#设置文字类型及字号
c.setFont('hei',20)
#生成一个table表格
atable = [[1,2,3,4],[5,6,7,8]]
t = Table(atable,50,20)
t.setStyle(TableStyle([('ALIGN',(0,0),(3,1),'CENTER'),
                       ('INNERGRID',(0,0),(-1,-1),0.25,colors.black),
                       ('BOX',(0,0),(-1,-1),0.25,colors.black)]))
textOb = c.beginText(1,ylength-10)
indexVlaue = 0
while(indexVlaue < ylength):
    textStr = '''test 中文写入测试中文写入测试中文写入测试中文写入测试%d'''%indexVlaue
    #print('nextline,nextline%d'%indexVlaue)
    textOb.textLine(textStr)
    indexVlaue = indexVlaue + 1
    break
c.drawText(textOb)
#简单的图片载入
imageValue = 'test.png'
c.drawImage(imageValue,97,97,300,300)
c.drawImage('test.png',50,50,50,50)
t.split(0,0)
t.drawOn(c,100,1)
c.showPage()
#换页的方式不同的showPage
c.drawString(0,0,'helloword')
c.showPage()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值