search
HomeBackend DevelopmentPython TutorialPython example detailed explanation of pdfplumber reading PDF and writing to Excel

This article brings you relevant knowledge about python, which mainly introduces the related issues about pdfplumber reading PDF and writing to Excel, including the installation of pdfplumber module, loading PDF, and Let’s take a look at some practical operations and so on. I hope it will be helpful to everyone.

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

Recommended learning: python video tutorial

1. Python operation PDF 13 large library comparison

PDF ( Portable Document Format) is a portable document format that facilitates the dissemination of documents across operating systems. PDF documents follow a standard format, so there are many tools that can operate on PDF documents, and Python is no exception.

Comparison chart of Python operating PDF modules is as follows:

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

This article mainly introduces pdfplumberFocus on PDF content extraction, such as text (position, font and colors, etc.) and shapes (rectangles, straight lines, curves), as well as the function of parsing tables.

2. pdfplumber module

Several other Python libraries help users extract information from PDFs. As a broad overview, pdfplumber differentiates itself from other PDF processing libraries by combining the following features:

  • Easy access to detailed information about each PDF object
  • Used for Higher-level, customizable methods for extracting text and tables
  • Tightly integrated visual debugging
  • Other useful utility features such as filtering objects by crop boxes

1. Installation

cmd console input:

pip install pdfplumber

Guide package:

import pdfplumber

Case PDF screenshot (two pages are not cut off):
Python example detailed explanation of pdfplumber reading PDF and writing to Excel

2. Load PDF

Read PDF code: pdfplumber.open("path/filename.pdf", password = "test", laparams = { "line_overlap": 0.7 })

Parameter interpretation:

  • password : To load a password-protected PDF, please pass the password keyword parameter
  • laparams: To set the layout analysis parameters to the layout engine of pdfminer.six, pass the laparams keyword argument

Case code:

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    print(pdf)
    print(type(pdf))

Output Result:

<pdfplumber.pdf.pdf><class></class></pdfplumber.pdf.pdf>

3. pdfplumber.PDF class

pdfplumber.PDF class represents a single PDF and has two main properties:

From PDF Get the metadata Returns a list containing pdfplumber.Page instances, each instance represents the information of each page of the PDF
Properties Description
##.metadata key/value pair dictionary from Info. Usually includes "CreationDate", "ModDate", "Producer", etc.
.pages

1. Read PDF document information (.metadata) :

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    print(pdf.metadata)
Run result:

{'Author': 'wangwangyuqing', 'Comments': '', 'Company': '', 'CreationDate': "D:20220330113508+03'35'", 'Creator': 'WPS 文字', 'Keywords': '', 'ModDate': "D:20220330113508+03'35'", 'Producer': '', 'SourceModified': "D:20220330113508+03'35'", 'Subject': '', 'Title': '', 'Trapped': 'False'}

2. Output the total number of pages

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    print(len(pdf.pages))
Running result:

2
4. pdfplumber.Page class

pdfplumber.PageThe class is the core of pdfplumber. Most operations revolve around this class. It has the following attributes:

AttributesDescriptionSequential page numbers, starting from 1 on the first page, starting from the second page 2, and so on analogy. The width of the page. The height of the page. Each of these properties is a list, each containing a dictionary for each such object embedded on the page. See "Objects" below for details.
.page_number
.width
.height
.objects/.chars/.lines/.rects/.curves/.figures/.images

Commonly used methods are as follows:

Method nameDescription is used to extract the text in the page and organize all the character objects on the page into That string returns all the words and their related informationExtract the tables of the pageWhen used for visual debugging, return an instance of the PageImage classBy default, the Page object caches its layout and object information to avoid reprocessing it. However, these cached properties can require a lot of memory when parsing large PDFs. You can use this method to flush the cache and free up memory.

1. 读取第一页宽度、高度等信息

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    first_page = pdf.pages[0]  # pdfplumber.Page对象的第一页
    # 查看页码
    print('页码:', first_page.page_number)
    # 查看页宽
    print('页宽:', first_page.width)
    # 查看页高
    print('页高:', first_page.height)

运行结果:

页码: 1页宽: 595.3页高: 841.9

2. 读取文本第一页

import pdfplumberwith pdfplumber.open("./1.pdf") as pdf:
    first_page = pdf.pages[0]  # pdfplumber.Page对象的第一页
    text = first_page.extract_text()
    print(text)

运行结果:

店铺名 价格 销量 地址
小罐茶旗舰店 449 474 安徽
零趣食品旗舰店 6.9 60000 福建
天猫超市 1304 3961 上海
天猫超市 139 25000 上海
天猫超市 930 692 上海
天猫超市 980 495 上海
天猫超市 139 100000 上海
三只松鼠旗舰店 288 25000 安徽
红小厨旗舰店 698 1767 北京
三只松鼠旗舰店 690 15000 安徽
一统领鲜旗舰店 1098 1580 上海
新大猩食品专营9.8 7000 湖南.......舰店
蟹纳旗舰店 498 1905 上海
三只松鼠坚果at茶 188 35000 安徽
嘉禹沪晓旗舰店 598 1517 上海

3. 读取表格第一页

import pdfplumberimport xlwtwith pdfplumber.open("1.pdf") as pdf:
    page_one = pdf.pages[0]  # PDF第一页
    table_1 = page_one.extract_table()  # 读取表格数据
    # 1. 创建Excel表对象
    workbook = xlwt.Workbook(encoding='utf8')
    # 2. 新建sheet表
    worksheet = workbook.add_sheet('Sheet1')
    # 3. 自定义列名
    col1 = table_1[0]
    # print(col1)# ['店铺名', '价格', '销量', '地址']
    # 4. 将列属性元组col写进sheet表单中第一行
    for i in range(0, len(col1)):
        worksheet.write(0, i, col1[i])
    # 5. 将数据写进sheet表单中
    for i in range(0, len(table_1[1:])):
        data = table_1[1:][i]
        for j in range(0, len(col1)):
            worksheet.write(i + 1, j, data[j])
    # 6. 保存文件分两种格式
    workbook.save('test.xls')

运行结果:

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

三、实战操作

1. 提取单个PDF全部页数

测试代码:

import pdfplumberimport xlwtwith pdfplumber.open("1.pdf") as pdf:
    # 1. 把所有页的数据存在一个临时列表中
    item = []
    for page in pdf.pages:
        text = page.extract_table()
        for i in text:
            item.append(i)
    # 2. 创建Excel表对象
    workbook = xlwt.Workbook(encoding='utf8')
    # 3. 新建sheet表
    worksheet = workbook.add_sheet('Sheet1')
    # 4. 自定义列名
    col1 = item[0]
    # print(col1)# ['店铺名', '价格', '销量', '地址']
    # 5. 将列属性元组col写进sheet表单中第一行
    for i in range(0, len(col1)):
        worksheet.write(0, i, col1[i])
    # 6. 将数据写进sheet表单中
    for i in range(0, len(item[1:])):
        data = item[1:][i]
        for j in range(0, len(col1)):
            worksheet.write(i + 1, j, data[j])
    # 7. 保存文件分两种格式
    workbook.save('test.xls')

运行结果(上面得没截全):

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

2. 批量提取多个PDF文件

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

测试代码:

import pdfplumber
import xlwt
import os

# 一、获取文件下所有pdf文件路径
file_dir = r'E:\Python学习\pdf文件'
file_list = []
for files in os.walk(file_dir):
    # print(files)
    # ('E:\\Python学习\\pdf文件', [],
    #  ['1.pdf', '1的副本.pdf', '1的副本10.pdf', '1的副本11.pdf', '1的副本2.pdf', '1的副本3.pdf', '1的副本4.pdf', '1的副本5.pdf', '1的副本6.pdf',
    #   '1的副本7.pdf', '1的副本8.pdf', '1的副本9.pdf'])
    for file in files[2]:
        # 以. 进行分割如果后缀为PDF或pdf就拼接地址存入file_list
        if file.split(".")[1] == 'pdf' or file.split(".")[1] == 'PDF':
            file_list.append(file_dir + '\\' + file)

# 二、存入Excel
# 1. 把所有PDF文件的所有页的数据存在一个临时列表中
item = []
for file_path in file_list:
    with pdfplumber.open(file_path) as pdf:
        for page in pdf.pages:
            text = page.extract_table()
            for i in text:
                item.append(i)

# 2. 创建Excel表对象
workbook = xlwt.Workbook(encoding='utf8')
# 3. 新建sheet表
worksheet = workbook.add_sheet('Sheet1')
# 4. 自定义列名
col1 = item[0]
# print(col1)# ['店铺名', '价格', '销量', '地址']
# 5. 将列属性元组col写进sheet表单中第一行
for i in range(0, len(col1)):
    worksheet.write(0, i, col1[i])
# 6. 将数据写进sheet表单中
for i in range(0, len(item[1:])):
    data = item[1:][i]
    for j in range(0, len(col1)):
        worksheet.write(i + 1, j, data[j])
# 7. 保存文件分两种格式
workbook.save('test.xls')

运行结果(12个文件,一个文件50行总共600行):

Python example detailed explanation of pdfplumber reading PDF and writing to Excel

推荐学习:python视频教程

.extract_text()
.extract_words()
.extract_tables()
.to_image()
.close()

The above is the detailed content of Python example detailed explanation of pdfplumber reading PDF and writing to Excel. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools