python实现word转pdf

这是一个使用 Flask 框架和 win32com 库来实现将上传的 Microsoft Word 文档转换为 PDF 格式的简单网络应用程序。

  1. 首先,导入所需的库和模块:

    • Flask:用于创建 Web 应用程序。
    • request:用于处理请求数据,例如上传的文件。
    • send_file:用于发送文件作为响应。
    • win32com.client:这是 PyWin32 库的一部分,用于操作 Windows COM(Component Object Model)对象,这里主要用于与 Microsoft Word 进行交互。
    • constants:从 win32com.client 导入的 Word 常量。
    • gencache:用于生成 COM 对象的缓存。
  2. 创建 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>

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值