这是一个使用 Flask 框架和 win32com 库来实现将上传的 Microsoft Word 文档转换为 PDF 格式的简单网络应用程序。
-
首先,导入所需的库和模块:
Flask
:用于创建 Web 应用程序。request
:用于处理请求数据,例如上传的文件。send_file
:用于发送文件作为响应。win32com.client
:这是 PyWin32 库的一部分,用于操作 Windows COM(Component Object Model)对象,这里主要用于与 Microsoft Word 进行交互。constants
:从win32com.client
导入的 Word 常量。gencache
:用于生成 COM 对象的缓存。
-
创建 Flask 应用实例:
from flask import Flask, request, send_file from win32com.client import constants, gencache import os app = Flask(__name__) # Word to PDF method def Word_to_Pdf(Word_path, Pdf_path): word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(Word_path, ReadOnly=1) # Convert the document to PDF doc.ExportAsFixedFormat(Pdf_path, constants.wdExportFormatPDF) word.Quit() @app.route('/convert', methods=['POST']) def convert_word_to_pdf(): # Check if a file was uploaded if 'wordfile' not in request.files: return 'No file uploaded' word_file = request.files['wordfile'] # Save the uploaded Word file to a temporary location temp_path = os.path.join(os.getcwd(), 'temp.docx') word_file.save(temp_path) # Generate the PDF file path pdf_path = os.path.join(os.getcwd(), 'converted.pdf') try: # Convert the Word file to PDF Word_to_Pdf(temp_path, pdf_path) # Remove the temporary Word file os.remove(temp_path) # Return the URL of the converted PDF file return pdf_path except Exception as e: # Handle the conversion error return f'Error converting file: {str(e)}' @app.route('/') def index(): # Return the HTML file for the frontend return send_file('index.html') if __name__ == '__main__': app.run()
前端代码
<!DOCTYPE html>
<html>
<head>
<title>Word to PDF Conversion</title>
<style>
body {
margin: 20px;
font-family: Arial, sans-serif;
}
form {
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1>Word to PDF Conversion</h1>
<form action="/convert" method="post" enctype="multipart/form-data">
<input type="file" name="wordfile">
<button type="submit">Convert</button>
</form>
<div id="result"></div>
<script>
const form = document.querySelector('form');
const resultDiv = document.getElementById('result');
form.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(form);
fetch('/convert', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
const downloadLink = document.createElement('a');
downloadLink.href = data;
downloadLink.download = 'converted.pdf';
downloadLink.textContent = 'Download PDF';
resultDiv.innerHTML = '';
resultDiv.appendChild(downloadLink);
})
.catch(error => {
resultDiv.innerHTML = 'Error converting file.';
console.error(error);
});
});
resultDiv.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
e.target.click();
}
});
</script>
</body>
</html>