word转换服务python版本
网页无法打开word文档。但是可以转换为pdf来在网页上找开。用python实现在线转换服务。
from flask import Flask, request, jsonify,redirect,send_from_directory from win32com.client import constants,gencache import requests import os import pythoncom app = Flask(__name__) #定义pdf方法 ''' wordPath:word的文件路径 pdfPath:pdf生成的路径 ''' def Word_to_Pdf(Word_path,Pdf_path): pythoncom.CoInitialize() word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(Word_path,ReadOnly = 1) # 转换方法 doc.ExportAsFixedFormat(Pdf_path,constants.wdExportFormatPDF) word.Quit() @app.route('/convert', methods=['POST']) def convert_file(): file_url = request.json.get('fileurl') # 获取JSON请求中的文件地址参数 if not file_url: return jsonify({'error': '文件参数错误'}), 400 # 如果没有传递文件地址参数,返回错误 doc_filename = file_url.split('/')[-1] # 提取文件名 doc_filepath = os.path.join(os.getcwd()+'./tmp', doc_filename) # 临时文件路径 pdf_filename = doc_filename.split('.')[0] + '.pdf' # 将文件名后缀更改为.pdf pdf_filepath = os.path.join(os.getcwd()+'/tmp', pdf_filename) # 临时PDF文件路径 r = requests.get(file_url) with open(doc_filepath,"wb") as code: code.write(r.content) print(doc_filepath) print(pdf_filepath) try: Word_to_Pdf(doc_filepath, pdf_filepath) # 将Word文档转换为PDF except Exception as e: return jsonify({'error': str(e)}), 500 # 转换失败,返回错误 return jsonify({'pdfurl': f'http://localhost:88/pdf/{pdf_filename}'}), 200 # 如果成功,返回PDF文件地址 @app.route('/pdf/<filename>', methods=['GET']) def get_pdf(filename): root_dir = os.getcwd() print(os.path.join(root_dir, 'tmp')) return send_from_directory(os.path.join(root_dir, 'tmp'), filename) if __name__ == '__main__': app.run('127.0.0.1',"88")
上来代码已经通过测试。注意模块的安装。转换是调用的win32接口。请求使用json格式如下:
{ "fileurl": "http://www.028icp.com/upfiles/fujian/20101029152391314456.doc" }
请求地址是:http://127.0.0.1:88/convert
成功后返回的格式如下:
{ "pdfurl": "http://localhost:88/pdf/20101029152391314456.pdf" }