python word转图片、word转pdf、pdf转图片API版本

该代码实现了一个Python应用,它接收Word文档(doc或docx)或PDF,将其转换为PDF(如果上传的是Word),然后将PDF转换为一系列图片,并上传到七牛云存储。应用使用了Flask框架、win32com库处理Word,fitz库处理PDF,以及七牛云的API进行文件上传。
摘要由CSDN通过智能技术生成
#!/usr/bin/env python3
# coding=utf-8


import fitz
import os
import uuid
import time
from win32com.client import constants, gencache
from flask import Flask, request
import pythoncom
import json
from qiniu import Auth, put_file, etag
import qiniu.config

# 七牛云 需要填写你的 Access Key 和 Secret Key
access_key = ''
secret_key = ''
# 构建鉴权对象
q = Auth(access_key, secret_key)
# 要上传的空间
bucket_name = ''
# 七牛云域名
domain = '/' # 域名后面要有斜杠
app = Flask(__name__)

osPath = os.getcwd()


def docToPdf(wordPath, fileDir):
    pythoncom.CoInitialize()
    # 调用word程序
    word = gencache.EnsureDispatch('Word.Application')
    # 打开word文件
    doc = word.Documents.Open(wordPath, ReadOnly=1)
    # 文件名要全部
    uuids = uuid.uuid1()
    pdfPath = fileDir + '/pdf/' + str(uuids) + '.pdf'
    doc.ExportAsFixedFormat(pdfPath, constants.wdExportFormatPDF)
    # 转图片
    pythoncom.CoUninitialize()
    return pdfToImg(pdfPath, fileDir)


# 上传到七牛云
def uploadToQiniu(fileDir):
    fileData = fileDir + '/change'
    uuids = uuid.uuid1()
    fielList = []
    for dir, data, files in os.walk(fileData):
        for file in files:
            filename = 'doc/' + str(uuids) + '/' + file
            fielPath = r'' + fileData + '/' + file
            token = q.upload_token(bucket_name, filename, 3600)
            localfile = fielPath
            ret, info = put_file(token, filename, localfile, version='v2')
            if ret['key'] is not None:
                fielList.append(domain + ret['key'])
    return fielList


# pdf 转图片
def pdfToImg(pdf, fileDir):
    doc = fitz.open(pdf)
    for pg in range(0, doc.pageCount):
        page = doc[pg]
        rotate = int(0)  
        zoom_x = 2.0
        zoom_y = 2.0
        trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
        pm = page.getPixmap(matrix=trans, alpha=False)
        pm.writePNG(fileDir + '/change/' + '{:02}.png'.format(pg))
    return uploadToQiniu(fileDir)


# 创建文件夹
def mkdir():
    uuids = uuid.uuid1()
    path = osPath + '/doc/' + str(uuids)
    os.mkdir(path)
    pathDoc = osPath + '/doc/' + str(uuids) + '/doc'
    os.mkdir(pathDoc)
    pathPdf = osPath + '/doc/' + str(uuids) + '/pdf'
    os.mkdir(pathPdf)
    pathChange = osPath + '/doc/' + str(uuids) + '/change'
    os.mkdir(pathChange)
    return path


@app.route('/docChange', methods=['POST'])
def docChange():
    file = request.files['file']
    fileType = file.mimetype
    fileDir = mkdir()  # 文件存放的目录
    times = int(time.time())
    if fileType == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
        fileName = str(times) + '.docx'
        file.save(fileDir + '/doc/' + fileName)
        res = docToPdf(r'' + fileDir + '/doc/' + fileName, r'' + fileDir)
    elif fileType == 'application/msword':
        fileName = str(times) + '.doc'
        file.save(r'' + fileDir + '/doc/' + fileName)
        res = docToPdf(r'' + fileDir + '/doc/' + fileName, r'' + fileDir)
    elif fileType == 'application/pdf':
        fileName = str(times) + '.pdf'
        file.save(fileDir + '/pdf/' + fileName)
        res = pdfToImg(fileDir + '/pdf/' + fileName, fileDir)
    else:
        return json.dumps({'status': 203, 'err_msg': '错误的文档类型,只支持doc、docx、pdf'}, ensure_ascii=False)
    return json.dumps({'status': 200, 'err_msg': '转换成功', 'dataList': res}, ensure_ascii=False)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值