Win下Python通过Word/WPS更新文档目录、目录页数、转pdf

# -*- 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)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wufucks

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值