本文部分内容参考,如有侵权请联系删除:使用 easyofd 解析ofd 文件_python模块easyofd如何使用-CSDN博客
背景需求:需要将邮箱中得ofd格式发票提取出来转换成pdf或者图片。
在网上搜了发现使用pyofd包,安装之后使用各种问题,所以在PyPi上找了下发现包不多,最新得是easyofd,并且开发者最新还在更新,所以果断转到easyofd包上来,但是这块有一个很重要得必坑得就是最好从github上下载最新得包安装并使用,要不然版本不对还是会报错。开始由于版本不对,参考博客内容运行,发现有问题,于是看引用发现版本不对,所以最好还是用最新得,我这版是:, 下载地址:
https://github.com/renoyuan/easyofd ,
运行代码如下:
python
import requests
import urllib
from PIL import Image
from easyofd.ofd import OFD
import base64
def ofd_to_images(ofd_path, images_path, filename):
with open(ofd_path + filename,"rb") as f:
ofdb64 = str(base64.b64encode(f.read()),"utf-8")
ofd = OFD() # 初始化OFD 工具类
ofd.read(ofdb64,save_xml=False, xml_name="testxml") # 读取ofdb64
# print(ofd.data) # ofd.data 为程序解析结果
img_np = ofd.to_jpg() # 转图片
for idx, img in enumerate(img_np):
im = Image.fromarray(img)
im.save(f'%s.png' % (images_path + filename[:-4], ))
def ofd_to_pdf(ofd_path, images_path, filename):
with open(ofd_path + filename,"rb") as f:
ofdb64 = str(base64.b64encode(f.read()),"utf-8")
ofd = OFD() # 初始化OFD 工具类
ofd.read(ofdb64,save_xml=False, xml_name="testxml") # 读取ofdb64
# print(ofd.data) # ofd.data 为程序解析结果
pdf_bytes = ofd.to_pdf() # 转pdf
with open(f'%s.pdf' % (images_path + filename[:-4], ), "wb") as f:
f.write(pdf_bytes)
if __name__ == "__main__":
# 将ofd转成pdf
ofd_to_pdf(ofd_file_folder, pdf_file_folder, filename)
# 将ofd转成images
ofd_to_images(ofd_file_folder, img_file_folder, filename)