• 技术文章 >Python技术 >Python基础教程

    进阶PDF,就用Python(pdfminer.six和pdfplumber模块)

    2020-10-27 17:57:38原创14075
    继上篇讲过PDF中的PyPDF2模块后,本篇为大家带来pdfminer.sixpdfplumber模块的详细讲解。


    pdfminer.six


    PDFMiner的操作门槛比较高,需要部分了解PDF的文档结构模型,适合定制开发复杂的内容处理工具。

    平时直接用PDFMiner比较少,这里只演示基本的文档内容操作:


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">import pathlib

    from pdfminer.pdfparser import PDFParser

    from pdfminer.pdfdocument import PDFDocument

    from pdfminer.pdfpage import PDFPage

    from pdfminer.pdfinterp import PDFResourceManager

    from pdfminer.pdfinterp import PDFPageInterpreter

    from pdfminer.pdfdevice import PDFDevice

    from pdfminer.layout import LAParams, LTTextBox, LTFigure, LTImage

    from pdfminer.converter import PDFPageAggregator

     

    path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf')

    f_path = path.joinpath('2020-新冠肺炎疫情对中国连锁餐饮行业的影响调研报告-中国连锁经营协会.pdf')

     

    with open(f_path, 'rb') as f:

        parser = PDFParser(f)

        doc = PDFDocument(parser)

        rsrcmgr = PDFResourceManager()

        laparams = LAParams()

        device = PDFPageAggregator(rsrcmgr, laparams=laparams)

        interpreter = PDFPageInterpreter(rsrcmgr, device)

        for page in PDFPage.create_pages(doc):

            interpreter.process_page(page)

            layout = device.get_result()

            for x in layout:

                # 获取文本对象

                if isinstance(x, LTTextBox):

                    print(x.get_text().strip())

                # 获取图片对象

                if isinstance(x,LTImage):

                    print('这里获取到一张图片')

                # 获取 figure 对象

                if isinstance(x,LTFigure):

                    print('这里获取到一个 figure 对象')<br></span></p>


    虽然pdfminer使用门槛较高,但遇到复杂情况,最后还得用它。目前开源模块中,它对PDF的支持应该是最全的了。

    下面这个pdfplumber就是基于pdfminer.six开发的模块,降低了使用门槛。


    pdfplumber


    相比pdfminer.six,pdfplumber提供了更便捷的PDF内容抽取接口。

    日常工作中常用的操作,比如:


    提取PDF内容,保存到txt文件


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">import pathlib

    import pdfplumber

     

    path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf')

    f_path = path.joinpath('2020-新冠肺炎疫情对中国连锁餐饮行业的影响调研报告-中国连锁经营协会.pdf')

    out_path = path.joinpath('002pdf_out.txt')

     

    with pdfplumber.open(f_path) as pdf, open(out_path ,'a') as txt:

        for page in pdf.pages:

            textdata = page.extract_text()

            txt.write(textdata)<br></span></p>


    提取PDF中的表格到Excel


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">import pathlib

    import pdfplumber

    from openpyxl import Workbook

     

    path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf')

    f_path = path.joinpath('2020-新冠肺炎疫情对中国连锁餐饮行业的影响调研报告-中国连锁经营协会.pdf')

    out_path = path.joinpath('002pdf_excel.xlsx')

     

    wb = Workbook()

    sheet = wb.active

    with pdfplumber.open(f_path) as pdf:

        for i in range(19, 22):

            page = pdf.pages[i]

            table = page.extract_table()

            for row in table:

                sheet.append(row)

    wb.save(out_path)<br></span></p>


    上面用到了openpyxl的功能创建了一个Excel文件,之前有单独文章介绍它。


    提取PDF中的图片


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">import pathlib

    import pdfplumber

    from PIL import Image

     

    path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf')

    f_path = path.joinpath('2020-疫情影响下的中国社区趋势研究-艾瑞.pdf')

    out_path = path.joinpath('002pdf_images.png')

    with pdfplumber.open(f_path) as pdf, open(out_path, 'wb') as fout:

        page = pdf.pages[10]

        # for img in page.images:

        im = page.to_image()

        im.save(out_path, format='PNG')

        imgs = page.images

        for i, img in enumerate(imgs):

            size = img['width'], img['height']

            data = img['stream'].get_data()

            out_path = path.joinpath(f'002pdf_images_{i}.png')

            with open(out_path, 'wb') as fimg_out:

                fimg_out.write(data)<br></span></p>


    上面用到了PIL(Pillow)的功能处理图片。


    提取PDF中的图表


    图表与图像不同,指的是类似直方图、饼图之类的数据生成图。


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">import pathlib

    import pdfplumber

    from PIL import Image

     

    path = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/002pdf')

    f_path = path.joinpath('2020-新冠肺炎疫情对中国连锁餐饮行业的影响调研报告-中国连锁经营协会.pdf')

    out_path = path.joinpath('002pdf_figures.png')

    with pdfplumber.open(f_path) as pdf, open(out_path, 'wb') as fout:

        page = pdf.pages[7]

        im = page.to_image()

        im.save(out_path, format='PNG')

        figures = page.figures

        for i, fig in enumerate(figures):

            size = fig['width'], fig['height']

            crop = page.crop((fig['x0'], fig['top'], fig['x1'], fig['bottom']))

            img_crop = crop.to_image()

            out_path = path.joinpath(f'002pdf_figures_{i}.png')

            img_crop.save(out_path, format='png')

        im.draw_rects(page.extract_words(), stroke='yellow')

        im.draw_rects(page.images, stroke='blue')

        im.draw_rects(page.figures)

    im # show in notebook<br></span></p>


    另外需要说明的是,PDF标准规范由Adobe公司主导。

    平时我们不需要参考规范,但如果遇到一些较复杂的场景,尤其是模块没有直接支持,就只能硬着头皮翻阅文档了。文档是公开的,可以去搜索引擎搜索关键词:pdf_reference_1-7.pdf


    今天的分享到这里就结束了,希望能让大家对使用PDF有了更多的理解和运用。更多Python学习,就在PyThon学习网教学中心

    专题推荐:pdf;python
    上一篇:Python基础之openpyxl如何实现vlookup函数 下一篇:python如何合并列表?怎么做?

    相关文章推荐

    • 如何把python中的数据导入excel

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网