python进阶:PDF电子发票读取与合并
off999 2024-09-21 20:58 36 浏览 0 评论
大部分公司还是需要员工自行整理发票填写报销单,并且打印电子发票后提交给财务才能报销。如果发票多了会很浪费时间,让我们用Python写个程序来管理电子发票吧。
个人发票管理功能点
- 发票自动识别,读取发票信息。(前期只处理PDF电子发票)
- 批量导出识别的发票信息。
- 合并多个发票文件到一个文件。
后续增加功能。会陆续写文章一步一步介绍如何实现这些功能。
- 提供可视化界面,支持C/S和B/S两种模式。
- 添加到windows任务栏。
- 发票分类。根据报销类型对发票进行分类标注。
- 发票抬头、税号、发票号等校验,排除错误抬头、避免出现重复发票。
- 标注已经报销的发票。
- 自动读取邮箱中的发票附件,并提取发票信息。
- 支持图片格式增值税发票。基于OCR识别发票。
- 支持更多其他类型的发票。
PDF格式电子发票信息读取
Python处理PDF的库很多,有PyMuPDF、PyPDF2、pdfminer、pdfplumber等,每个库都有不同的特点(使用Python操作PDF:常用PDF库总结 - 知乎这篇文章总结得比较全面,有兴趣的可以看看)。
我选择用pdfplumber(https://github.com/jsvine/pdfplumber)这个库来读取发票内容,因为它可以方便的提取PDF中的文本、图片,重要的是它可以很好地提取表格。
安装pdfplumber
pip install pdfplumber下面的示例代码将打印出pdfplumber读取的文本信息和表格信息,并且将pdf表格和文本框保存到图片查看读取效果。另外,电子发票含有一个二维码,里面包含发票信息,pdfplumber没有办法直接解析出图片,这里使用crop()函数截取图片区域,然后再用to_image()函数转成图片。二维码图片可以用pyzbar等识别二维码的库解析,用于核对信息。
import pdfplumber
with pdfplumber.open(r"1.pdf") as pdf:
# 读取第一页
first_page = pdf.pages[0]
# 转成图片,dpi设置为100
im = first_page.to_image(resolution=100)
# 画出表格边框和线条交点
im.debug_tablefinder()
# 画出文本边框
im.draw_rects(first_page.extract_words())
# 保存图片
im.save(r"1.png")
# 打印读取的文本
print(first_page.extract_text())
# 打印读取的表格
print(first_page.extract_table())
# 保存pdf中的图片
for image in first_page.images:
im = first_page.crop(bbox=(image['x0'],image['top'],image['x1'],image['bottom'])).to_image(resolution=100)
im.save(f"{image['name']}.png")
从上图可以看出pdfplumber识别发票表格的效果还是很好的,红色线是识别的表格,蓝色圆圈点是表格线条的交点。
另外通过extract_text()打印出来的文本,我们分析可以发现,直接从文本中获取发票全部信息还是比较困难的(懒得打码就不放图了),很多信息混在一起。这个换别的库提取文本也一样,都没有很好的效果,而且不同省份的发票PDF排版还不一样,如果不通过表格区域去获取文本,是没有办法解析发票全部信息的。
最后,我们结合extract_text()和extract_table()分别获取发票头和发票表格中的信息。
解析发票信息并导出到表格
解析发票比较简单,用正则表达式提取信息就可以了。以发票表格上方的发票号等信息为例,通过extract_text()获取的文本来解析(需要注意的是不同地区发票的“冒号”有的是半角有的是全角):
# 提取发票表格上方内容
invoice.number = re.search(r'发票号码(:|:)(\d+)', text).group(2)
invoice.date = re.search(r'开票日期(:|:)(.*)', text).group(2)
invoice.machine_number = re.search(r'机器编号(:|:)(\d+)', text).group(2)
invoice.code = re.search(r'发票代码(:|:)(\d+)', text).group(2)
invoice.check_code = re.search(r'校验码(:|:)(\d+)', text).group(2)发票表格中的内容,则通过extract_table()获取的表格内容来解析。以购买方为例,需要从指定的cell中去获取数据:
# 读取表格
table = first_page.extract_table()
# 表格为4行11列
# ‘购买方’,内容,none,none,none,none,‘密码区’,密码,none,none,none
# 货物名,none,规格,单位,数量,单价,none,none,金额,税率,税额
# ‘价税合计’,none,金额,none,none,none,none,none,none,none,none
# ‘销售方’,内容,none,none,none,none,‘备注’,备注,none,none,none
# 购买方
purchaser = table[0][1].replace(" ", "")
purchaser_name = re.search(r'名称(:|:)(.+)', purchaser)
invoice.purchaser_name = purchaser_name.group(2) if purchaser_name else ''
purchaser_tax_number = re.search(r'纳税人识别号(:|:)(.+)', purchaser)
invoice.purchaser_tax_number = purchaser_tax_number.group(2) if purchaser_tax_number else ''
purchaser_address = re.search(r'地址、电话(:|:)(.+)', purchaser)
invoice.purchaser_address = purchaser_address.group(2) if purchaser_address else ''
purchaser_bank = re.search(r'开户行及账号(:|:)(.+)', purchaser)
invoice.purchaser_bank = purchaser_bank.group(2) if purchaser_bank else ''导出数据到excel
使用openpyxl可以很简单地将识别到的发票数据导出到excel文件。
workbook = openpyxl.Workbook()
sheet=workbook[workbook.sheetnames[0]]
# 导出开票日期、发票代码、发票号码、校验码、购买方名称和税号、销售方名称和税号、价格、税率、税额、价税合计、备注
sheet.append(['开票日期','发票代码','发票号码','校验码','购买方名称','购买方税号','销售方名称','销售方税号','价格','税率','税额','价税合计','备注'])
for i in range(row):
invoice = invoices[i]
sheet.append([invoice.date,invoice.code,invoice.number,invoice.check_code,invoice.purchaser_name,invoice.purchaser_tax_number,invoice.seller_name,invoice.seller_tax_number,invoice.total_amount,invoice.tax_rate,invoice.total_tax,invoice.total,invoice.remark])
workbook.save(output_path)导出表格示例如下图:
合并发票文件
由于pdfplumber不能很好的编辑PDF文件,这里我们使用PyPDF4来处理PDF的合并,代码也很简单:
from PyPDF4 import PdfFileMerger
merger = PdfFileMerger()
for invoice_path in invoice_paths:
merger.append(invoice_path)
merger.write(output_path)
merger.close()为了节省纸张,有些公司会在一张A4纸打印2张发票,这里我们不去实现两张发票合并到一个页面的功能,这个可以在文件打印的时候选择一页打印多张PDF。
源码
最后,干货必须带源码~
python版本为3.8,需要安装的依赖包如下requirements.txt:
pdfplumber~=0.6.1
PyPDF4~=1.27.0
openpyxl~=3.0.7invoice.py
import pdfplumber
from PyPDF4 import PdfFileMerger
import openpyxl
import re,time,os
class Invoice:
def __init__(self):
# 发票类型、发票号码、开票日期、机器编号、发票代码、校验码
self.type=self.number=self.date=self.machine_number=self.code=self.check_code = ''
# 收款人、复核、开票人
self.payee=self.reviewer=self.drawer = ''
# 购买方名称、纳税人识别号、地址电话、开户行及账号
self.purchaser_name=self.purchaser_tax_number=self.purchaser_address=self.purchaser_bank = ''
# 密码
self.password = ''
# 合计金额、合计税额、税率、价税合计
self.total_amount=self.total_tax=self.tax_rate=self.total = ''
# 销售方名称、纳税人识别号、地址电话、开户行及账号
self.seller_name=self.seller_tax_number=self.seller_address=self.seller_bank = ''
# 备注
self.remark = ''
# 解析PDF格式电子发票
@staticmethod
def read_invoice(pdf_file: str) -> "Invoice":
invoice = Invoice()
try:
with pdfplumber.open(pdf_file) as pdf:
# 读取第一页
first_page = pdf.pages[0]
# 读取文本
text = first_page.extract_text().replace(" ", "")
# print(text)
if '专用发票' in text:
invoice.type = '专票'
elif '普通发票' in text:
invoice.type = '普票'
else:
raise Exception('未知发票类型或非发票文件')
# 提取发票表格上方内容
invoice.number = re.search(r'发票号码(:|:)(\d+)', text).group(2)
invoice.date = re.search(r'开票日期(:|:)(.*)', text).group(2)
invoice.machine_number = re.search(r'机器编号(:|:)(\d+)', text).group(2)
invoice.code = re.search(r'发票代码(:|:)(\d+)', text).group(2)
invoice.check_code = re.search(r'校验码(:|:)(\d+)', text).group(2)
# 提取发票表格下方内容,全在一行里
match = re.search(r'.*收款人(:|:)(.*)复核(:|:)(.*)开票人(:|:)(.*)销售', text)
invoice.payee = match.group(2)
invoice.reviewer = match.group(4)
invoice.drawer = match.group(6)
# 读取表格
table = first_page.extract_table()
# 表格为4行11列
# ‘购买方’,内容,none,none,none,none,‘密码区’,密码,none,none,none
# 货物名,none,规格,单位,数量,单价,none,none,金额,税率,税额
# ‘价税合计’,none,金额,none,none,none,none,none,none,none,none
# ‘销售方’,内容,none,none,none,none,‘备注’,备注,none,none,none
if table and len(table)==4:
# 购买方
purchaser = table[0][1].replace(" ", "")
purchaser_name = re.search(r'名称(:|:)(.+)', purchaser)
invoice.purchaser_name = purchaser_name.group(2) if purchaser_name else ''
purchaser_tax_number = re.search(r'纳税人识别号(:|:)(.+)', purchaser)
invoice.purchaser_tax_number = purchaser_tax_number.group(2) if purchaser_tax_number else ''
purchaser_address = re.search(r'地址、电话(:|:)(.+)', purchaser)
invoice.purchaser_address = purchaser_address.group(2) if purchaser_address else ''
purchaser_bank = re.search(r'开户行及账号(:|:)(.+)', purchaser)
invoice.purchaser_bank = purchaser_bank.group(2) if purchaser_bank else ''
# 密码区
invoice.password = table[0][7].replace("\n", "")
# 合计金额、税额
invoice.total_amount = table[1][8].split("\n")[-1].replace("¥", "").replace(" ", "").replace(",", "")
invoice.total_amount = float(invoice.total_amount)
# 注意有的发票税额为0是'*',无法直接转成数值
invoice.total_tax = table[1][10].split("\n")[-1].replace("¥", "").replace(" ", "").replace("*", "0").replace(",", "")
invoice.total_tax = float(invoice.total_tax) if invoice.total_tax else 0
# 税率,一般一张发票中货品税率一致;也可以用(总税额/总金额)计算税率
invoice.tax_rate = table[1][9].split("\n")[-1].replace(" ", "").replace("%", "").replace("*", "0")
invoice.tax_rate = float(invoice.tax_rate)/100 if invoice.tax_rate else 0
# invoice.tax_rate = invoice.total_tax / invoice.total_amount
# 价税合计,解析或计算
invoice.total = re.search(r'.+¥(.+)', table[2][2]).group(1).replace(" ", "").replace(",", "")
invoice.total = float(invoice.total)
# invoice.total = invoice.total_tax + invoice.total_amount
# 销售方
seller = table[3][1].replace(" ", "")
invoice.seller_name = re.search(r'名称(:|:)(.+)', seller).group(2)
invoice.seller_tax_number = re.search(r'纳税人识别号(:|:)(.+)', seller).group(2)
seller_address = re.search(r'地址、电话(:|:)(.+)', seller)
invoice.seller_address = seller_address.group(2) if seller_address else ''
seller_bank = re.search(r'开户行及账号(:|:)(.+)', seller)
invoice.seller_bank = seller_bank.group(2) if seller_bank else ''
# 备注
invoice.remark = table[3][7].replace("\n", "")
except Exception as e:
print(pdf_file, e)
return invoice
#导出到excel
@staticmethod
def export_to_excel(invoices:"list[Invoice]", output_path:str):
row = len(invoices) if invoices else 0
if row == 0:
print("没有可导出的数据")
return
try:
workbook = openpyxl.Workbook()
sheet=workbook[workbook.sheetnames[0]]
# 导出开票日期、发票代码、发票号码、校验码、购买方名称和税号、销售方名称和税号、价格、税率、税额、价税合计、备注
sheet.append(['开票日期','发票代码','发票号码','校验码','购买方名称','购买方税号','销售方名称','销售方税号','价格','税率','税额','价税合计','备注'])
for i in range(row):
invoice = invoices[i]
sheet.append([invoice.date,invoice.code,invoice.number,invoice.check_code,invoice.purchaser_name,invoice.purchaser_tax_number,invoice.seller_name,invoice.seller_tax_number,invoice.total_amount,invoice.tax_rate,invoice.total_tax,invoice.total,invoice.remark])
workbook.save(output_path)
except Exception as e:
print('导出到excel失败', e)
# 合并pdf
@staticmethod
def merge_pdf(invoice_paths:"list[str]", output_path:str):
if len(invoice_paths) == 0:
print("没有可合并的pdf")
return
try:
merger = PdfFileMerger()
for invoice_path in invoice_paths:
merger.append(invoice_path)
merger.write(output_path)
merger.close()
except Exception as e:
print('合并pdf失败', e)
if __name__ == '__main__':
# 发票所在文件夹,使用绝对路径
path = r'E:\playground\python_tools\pdf'
# 输出文件路径
output_path = os.path.join(path, 'output')
if not os.path.exists(output_path):
os.makedirs(output_path)
# 发票内容列表
invoices = []
# 发票文件路径列表
invoice_paths = []
#列出目录的下所有文件
lists = os.listdir(path)
for item in lists:
if item.endswith('.pdf'):
item = os.path.join(path, item)
invoice = Invoice.read_invoice(item)
# 仅保存解析成功的pdf
if invoice and invoice.type:
invoices.append(invoice)
invoice_paths.append(item)
# 导出发票内容到excel
Invoice.export_to_excel(invoices, f'{output_path}/invoice_{time.strftime("%Y%m%d_%H%M%S", time.localtime())}.xlsx')
# 合并发票到一个pdf
Invoice.merge_pdf(invoice_paths, f'{output_path}/merged_invoice_{time.strftime("%Y%m%d_%H%M%S", time.localtime())}.pdf')相关推荐
- 云电脑app哪个好(手机云电脑app哪个最好)
-
答:以下是一些比较好的云电脑应用程序推荐:1.AnyDesk-支持Windows、MacOS、Linux、Android和iOS,可用于远程访问和控制PC或移动设备。2.Splashtop...
- 怎样注册邮箱163免费(怎样注册邮箱163免费账号)
-
一、工具:电脑(联网)、浏览器二、操作步骤:【1】打开浏览器,找到“163邮箱”,点击。【2】点击右边的“注册”。【3】网站默认注册手机号码邮箱,填写信息,点击“注册”。若不想泄漏手机号码或不想使用手...
- 微软surface pro 6(微软surface pro 6可以扩容吗)
-
SurfacePro6的接口包含:1个标准尺寸USB3.0端口,3.5mm耳机插孔,MiniDisplayPort,1个SurfaceConnect端口,Surface专业键盘盖端口,microSDX...
- 电源已接通未充电怎么回事(电源已接通未充电 真正解决办法)
-
原因分析:出现这样的原因有可能是长时间没有充电,导致电池的内部电量耗完后亏电严重,只是电脑充电的保护,不让过充而已,只要设置一下电池选项一般就可以解决问题了。解决方法:1、关机,拔下电源,拔出电池,...
- 华为云会议app下载(华为云会议下载)
-
华为云会议可以在PC客户端或者手机客户端上一键发起立即会议,1秒创会。然后在会中选择企业通讯录中的人加入,系统会自动呼叫这些与会人,接听后即加入会议。ZOOM是一个云会议服务平台,为客户提...
- 路由器重置方法(路由器重置方法详细步骤)
-
路由器靠近WAN口边上的有一个小孔用于路由器的重置,路由器配置完成后,我们可能会忘记他的用户名或者是密码,那么我们可以把它恢复到出厂设置,再靠近万口或电源之间,有一个小孔,用一个尖锐的金属查一下大约五...
- 100个有效qq号以及密码(有效qq号和密码大全)
-
如果你的电脑知识好的话,不妨用一些复合密码!SHIFT+一些特殊符号,字母,数字!虽然麻烦了点,但总比被人盗号了的好,是吧!最好还用手机绑定一下,这样的话方便改密码也不怕QQ被盗了哦。。。QQ密码找回...
- win10家庭中文版下载官网(windows10家庭中文版下载)
-
你好,激活Win10家庭中文版的方法:1.购买正版Win10家庭中文版激活码,然后在计算机上输入激活码,即可完成激活。2.如果您已经安装了Win10家庭中文版,但尚未激活,可以通过以下步骤激活:-...
- 电脑截图在哪里找(电脑截图在哪里找图片win10)
-
截图默认会保存在电脑的剪贴板中,可以通过以下步骤将其保存到本地:1.打开任意一款图片软件,如Paint、Photoshop、Word等。2.按下键盘上的Ctrl+V,或者在软件菜单栏中选择...
- 电脑里一堆microsoft visual
-
按照系统向下兼容原理,保留2010就可以了.1)你安装的时候是不是把创建快捷键的选项框都没选上,导致在开始菜单中没有找到相应的链接?2)去你的安装目录下,找到Microsoftvisualc++...
-
- windows无法识别usb(windows无法识别usb设备)
-
Windows无法识别USB,解决办法如下右键开始菜单打开设备管理器,在通用串行总线控制器中右键点击设备选择“卸载”,完成后重新启动计算机即可解决问题。这有可能是在组策略中禁用了USB口,可以使用快捷键【Win+R】运行gpedit.msc...
-
2025-11-10 11:51 off999
- bios能看到硬盘 开机找不到硬盘
-
bios里可以看到硬盘,说明硬盘已经被主板识别。进系统找不到,可能硬盘没分区,或者硬盘是动态磁盘,还没有导入或激活。按win+r,输入diskmgmt.msc回车,就打开磁盘管理了,在里面可以给新硬盘...
- 无线网有个红叉(无线网有个红叉,搜索不到网络)
-
连接失败,路由坏换路由,外网坏,报修无线网络处出现红叉表示设备无法正常工作。请检查网卡驱动是否正常,无线网络开关是否打开。解决方法:查看电脑是否有无线网络开关,且是否打开。进入设备管理器检查网卡驱动是...
- thinkpad笔记本官网首页(thinkpad官方商城)
-
官方网站 国内:http://www.thinkworld.com.cn 国内用户只需要访问国内即可。 ThinkPad,中文名为“思考本”,在2005年以前是IBMPC事业部旗下的便携式计算机...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
python入门到脱坑 输入与输出—str()函数
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
慕ke 前端工程师2024「完整」
-
失业程序员复习python笔记——条件与循环
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
