search
HomeBackend DevelopmentPython TutorialTips | Python automatically extracts and organizes PDF invoices in batches


This article shares a PDF-based Python office automation case solution, which was also proposed by a financial lady. Let’s first look at the real needs.

Description of requirements

There are multiple PDF type invoices in a certain folderTips | Python automatically extracts and organizes PDF invoices in batches

Each one Invoice PDF is a pure picture type, and the text information inside cannot be copied manually (in fact, most invoices can copy part of the text, but we will explain it in the form of pictures), as shown below: Tips | Python automatically extracts and organizes PDF invoices in batches

The requirements that need to be met are: obtain the total amount of , taxpayer identification number, and issuer , that is, the following three box positions: Tips | Python automatically extracts and organizes PDF invoices in batches

Finally combined with the batch Operation, after obtaining the above information, store it in Excel! Tips | Python automatically extracts and organizes PDF invoices in batches

Ideas and code implementation

The essence of the requirement is an image recognition problem, because the content in the PDF is of image type and cannot be pressed Conventional methods extract the text directly. The solution is to use optical character recognition (OCR) to recognize the text in the picture. But at the same time, it should be noted that PDF is not a picture after all. In order to complete OCR, in addition to OCR itself, Ghostscript and ImageMagick must be downloaded to complete type conversion. Taking the Windows system as an example, you need to install the following three software on your computer:

  1. Ghostscript 32-bit
  2. ImageMagick 32-bit
  3. tesseract-OCR 32-bit

There is no special place in downloading and installing the three software (tesseract configuration is slightly complicated, but there are many tutorials on the Internet, so I won’t go into details here. ), readers can search for download and configuration by themselves. The code is explained below. First import the required modules:

from wand.image import Image
from PIL import Image as PI
import pyocr
import pyocr.builders
import io
import re
import os
import shutil

For specific module uses, please refer to the specific code below. Among them, wand and pyocr need to be installed separately because they are non-standard libraries. Open the command line and enter:

pip install wand
pip install pyocr

This requirement also involves docking Excel. You can consider using the Workbook of the openpyxl library to create a new Excel file:

from openpyxl import Workbook

Put the invoice.pdf in the requirement on the desktop. The desktop path can be obtained through the following code based on the os module:

# 获取桌面路径包装成一个函数
def GetDesktopPath():
    return os.path.join(os.path.expanduser("~"), 'Desktop')

path = GetDesktopPath() + r'\发票.pdf'

Get the configured tesseract for later calling:

tool = pyocr.get_available_tools()[0]

通过 wand 模块将 PDF 文件转化为分辨率为 300 的 jpeg 图片形式:

image_pdf = Image(filename=path, resolution=300)
image_jpeg = image_pdf.convert('jpeg')

将图片解析为二进制矩阵:

image_lst = []
for img in image_jpeg.sequence:
    img_page = Image(image=img)
    image_lst.append(img_page.make_blob('jpeg'))

io 模块的 BytesIO 方法读取二进制内容为图片形式:

new_img = PI.open(io.BytesIO(image_lst[0]))
new_img.show()

接下来分别截取需要提取部位字符串的图片了,尽量让图片中只有需要识别的部分,获取识别出来容易简单处理获得需要的内容。

首先以总金额为例,截取图片用 image.crop((left, top, right, bottom)) 四个参数需要反复调试才能确定。经确定四个参数分别是 1600 760 1830 900,尝试截取和预览图片:

### 解析1Z开头码
left = 350
top = 600
right = 1300
bottom = 730
image_obj1 = new_img.crop((left, top, right, bottom))
image_obj1.show()
Tips | Python automatically extracts and organizes PDF invoices in batches

截取成功后可以交给 OCR 了,代码为 tool.image_to_string()

txt1= tool.image_to_string(image_obj1)
print(txt1)
Tips | Python automatically extracts and organizes PDF invoices in batches

同样,通过方位的调试就可以准确切割到需要的部分进行识别:

left = 560
top = 1260
right = 900
bottom = 1320
image_obj2 = new_img.crop((left, top, right, bottom))
# image_obj2.show()
txt2 = tool.image_to_string(image_obj2)
# print(txt2)

最后是开票人的识别Tips | Python automatically extracts and organizes PDF invoices in batches

left = 1420
top = 1420
right = 1700
bottom = 1500
image_obj3 = new_img.crop((left, top, right, bottom))
# image_obj3.show()
txt3 = tool.image_to_string(image_obj3)
# print(txt3)
Tips | Python automatically extracts and organizes PDF invoices in batches

需要确认识别的内容是否正确,如果识别正确率欠佳可以考虑通过图片处理技术消除噪声,也可以去官网下载更高精度的训练包提高识别的正确性

至此,我们成功的识别了总金额、纳税人识别号、开票人三个消息,接下来就通过非常熟悉的 openpyxl 写入Excel,并使用 os 模块实现批量操作即可

workbook = Workbook()
sheet = workbook.active
header = ['总金额', '纳税人识别号', '开票人']
sheet.append(header)
sheet.append([txt1, txt2, txt3])
workbook.save(GetDesktopPath() + r'\汇总.xlsx')
Tips | Python automatically extracts and organizes PDF invoices in batches

综上,整个需求就成功实现,从效果来看还是非常不错的!完整源码可由文中代码组合而成(已全部分享在文中),感兴趣的读者可以自己尝试!

最后想说的是,其实本文的案例可以衍生出很多实用的办公自动化脚本,例如

  • 批量计算发票金额并重命名文件夹
  • 根据发票类型批量分类
  • 根据发票批量制作报销单
  • ··· ···

The above is the detailed content of Tips | Python automatically extracts and organizes PDF invoices in batches. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Python当打之年. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software