# -*- coding: utf-8 -*-
import os
import subprocess
import time
import traceback
import pythoncom
from pdf2image import convert_from_bytes
from win32com import client
from flask import Flask, request, send_file, jsonify
import LogHandler
app = Flask(__name__)
@app.route("/to_pdf", methods=["POST"])
def save_file():
start_time = time.time()
pythoncom.CoInitialize()
pid = os.getpid()
print(f"当前Python进程的PID是:{pid}")
app.logger.info(f"当前Python进程的PID是:{pid}")
# word = client.DispatchEx("KWPS.Application")
word = client.DispatchEx("WORD.Application")
try:
print('docx转PDF任务开始')
app.logger.info('docx转PDF任务开始')
data = request.files
flag = request.form.get('flag', 'pdf')
file = data['file']
# 文件写入磁盘
filename = file.filename
file.save(os.path.join(r'D:\docx_to_pdf', filename))
print('文件保存完成')
app.logger.info('文件保存完成')
print(f'docx转PDF任务开始执行----{filename}')
app.logger.info(f'docx转PDF任务开始执行----{filename}')
docx_path = os.path.join(r'D:\docx_to_pdf', filename)
try:
# 启动Word应用程序
word.Visible = False # 背景运行,不显示Word窗口
# 打开文档
doc = word.Documents.Open(docx_path)
# 处理弹窗
word.DisplayAlerts = False
# 更新目录
print(f"判断flag类型,是否需要更新目录:{flag}")
app.logger.info(f"判断flag类型,是否需要更新目录:{flag}")
if flag == 'toc':
doc.TablesOfContents(1).UpdatePageNumbers()
doc.SaveAs(docx_path.replace('.docx', '.pdf'), FileFormat=17)
doc.Save()
doc.Close()
# 退出Word应用程序
word.Quit()
pythoncom.CoUninitialize()
print("文件处理完成")
app.logger.info("文件处理完成")
except Exception as e:
print(traceback.format_exc())
word.Quit()
pythoncom.CoUninitialize()
print(f"文件处理异常--traceback.format_exc()---{traceback.format_exc()}")
print(f"文件处理异常--eee-{e}")
app.logger.info(f"文件处理异常--traceback.format_exc()---{traceback.format_exc()}")
app.logger.info(f"文件处理异常--eee-{e}")
finally:
try:
if word:
word.Quit()
del word
except Exception as e:
pass
pythoncom.CoUninitialize()
print(f'任务耗时 {time.time() - start_time}')
app.logger.info(f'任务耗时 {time.time() - start_time}')
print(f'docx转PDF任务执行结束----{filename}')
app.logger.info(f'docx转PDF任务执行结束----{filename}')
except Exception as e:
print(traceback.format_exc())
word.Quit()
pythoncom.CoUninitialize()
print(f"文件处理异常--traceback.format_exc()---{traceback.format_exc()}")
print(f"文件处理异常--eee-{e}")
app.logger.info(f"文件处理异常--traceback.format_exc()---{traceback.format_exc()}")
app.logger.info(f"文件处理异常--eee-{e}")
return jsonify({'code': 204})
return jsonify({'code': 200})
@app.route("/html2pdf", methods=["POST"])
def html2pdf():
'''
wkhtmltopdf
:return:
'''
try:
print('html转PDF任务开始')
app.logger.info('html转PDF任务开始')
data = request
command = data.get_json().get('command')
print(command)
get_pdf = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=10000)
stdout, stderr = get_pdf.communicate()
if stderr:
raise subprocess.SubprocessError(stderr)
return send_file(command[-1])
except Exception as e:
print(traceback.format_exc())
return jsonify({'code': 204})
@app.route("/getDocxFile", methods=["POST"])
def getDocxFile():
'''
:return:
'''
try:
filename = request.get_json().get('filename')
print(f'文件名:{filename}')
app.logger.info(f'获取文件:{filename}')
if os.path.exists(os.path.join(r'D:\docx_to_pdf', filename)):
return send_file(os.path.join(r'D:\docx_to_pdf', filename))
except Exception as e:
print(traceback.format_exc())
return jsonify({'code': 204})
@app.route("/pdf2img", methods=["POST"])
def pdf2img():
try:
print('html转PDF任务开始')
app.logger.info('html转PDF任务开始')
print(request.files['file'].filename)
file = request.files['file']
pdf_name = file.filename.replace('pdf', 'png')
print(f'文件:{pdf_name}')
app.logger.info(f'获取文件:{pdf_name}')
images = convert_from_bytes(file.read(), dpi=300)
images[0].save(os.path.join(r'D:\pdf2img', pdf_name))
if os.path.exists(os.path.join(r'D:\pdf2img', pdf_name)):
return send_file(os.path.join(r'D:\pdf2img', pdf_name))
return jsonify({'code': 204})
except Exception as e:
print(traceback.format_exc())
return jsonify({'code': 204})
@app.route("/test", methods=["GET"])
def test():
return 'hello world'
if __name__ == '__main__':
app.debug = True
app.logger.addHandler(LogHandler.getLogHandler())
app.run(host='0.0.0.0', port=8100, threaded=True)
10-20
2739
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)