python pdf转word或excel
·
python pdf转word或excel
直接上源码
main
import gradio as gr
import pdf2docx as p2d
import Pdf2Excel as p2e
import utils.id.IdUtil as idUtil
def convert_pdf_to(pdf_file, pdf_pwd, pdf_to_type):
if pdf_to_type == "docx":
# Convert PDF to DOCX
cv = p2d.Converter(pdf_file, password=pdf_pwd)
tmp_file = f"./output_{idUtil.IdUtil.getUUid()}.docx"
cv.convert(tmp_file)
cv.close()
return tmp_file
else:
# Convert PDF to Excel
cv = p2e.Converter(pdf_file, password=pdf_pwd)
tmp_file = f"./output_{idUtil.IdUtil.getUUid()}.xlsx"
cv.convert(tmp_file)
return tmp_file
if __name__ == '__main__':
with gr.Blocks() as b:
gr.Markdown("PDF to ")
with gr.Row():
with gr.Column():
pdf_file = gr.File(label="PDF文件", file_types=[".pdf"], file_count="single")
pdf_pwd = gr.Text(label="密码,非必填")
pdf_to_type = gr.Radio(["docx", "excel"], label="输出格式", value="docx")
convert_btn = gr.Button("转换")
out_file = gr.File(label="输出文件")
convert_btn.click(convert_pdf_to, inputs=[pdf_file, pdf_pwd, pdf_to_type], outputs=[out_file],
trigger_mode="once")
b.launch(share=True)
Pdf2Excel
import tabula
import pandas as pd
class Converter:
def __init__(
self, pdf_file: str, password: str = None,
):
self.pdf_file = pdf_file
self.password = password
def convert(self, out_file: str):
excel_file = out_file if out_file.lower().endswith(".xlsx") else f"{out_file}.xlsx"
# 读取PDF文件中的所有表格
tables = tabula.read_pdf(self.pdf_file, password=self.password, pages='all', multiple_tables=True)
# 创建一个Excel写入器
writer = pd.ExcelWriter(excel_file)
# 将每个表格合并到一个数据框中
merged_table = pd.concat(tables, ignore_index=True)
# 将合并的表格写入Excel文件中的一个工作表
merged_table.to_excel(writer, sheet_name='All Tables', index=False)
# 保存Excel文件
writer.close()
return f"./{excel_file}"
IdUtil
import time
import uuid
class IdUtil:
# 获取一个UUid
@staticmethod
def getUUid(only: bool = False, notHandler: bool = False) -> str:
id = str(uuid.uuid1()) if only else str(uuid.uuid4()) + str(time.time()).split(".")[0]
if notHandler:
return id
else:
return "".join(id.split("-"))
更多推荐



所有评论(0)