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
Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

What is the difference between arrays and lists in Python?What is the difference between arrays and lists in Python?May 05, 2025 am 12:06 AM

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

What module is commonly used to create arrays in Python?What module is commonly used to create arrays in Python?May 05, 2025 am 12:02 AM

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment