python文件docx转pdf

centos部署的django项目,使用libreoffice做文件转换,官网给环境安装好libreoffice后,可使用命令行来进行转化

还可转换其他的各种格式,本文只做了pdf转换

python 复制代码
import subprocess    
import os    
  
def convert_to_pdf(input_file, output_file):    
    # 检查文件扩展名    
    if input_file.endswith('.docx'):    
        extension = '-convert-to pdf'    
    elif input_file.endswith('.doc'):    
        extension = '-filter pdfimport -close-early'    
    else:    
        raise ValueError('Unsupported file format')    
    
    # 构建命令行参数    
    command = f'libreoffice --headless --convert-to pdf --outdir {os.path.dirname(output_file)} {input_file}{extension}'    
    
    # 运行命令行命令    
    try:  
        subprocess.run(command, shell=True)    
    except subprocess.CalledProcessError as e:  
        print(f"Error occurred while converting the document: {e}")  
        return False  
    
    # 检查输出文件是否存在    
    if not os.path.exists(output_file):    
        raise FileNotFoundError(f'Failed to create {output_file}')    
    
# 使用示例    
input_file = 'path/to/input.docx'  # 替换为实际的输入文件路径    
output_file = 'path/to/output.pdf'  # 替换为实际的输出文件路径    
convert_to_pdf(input_file, output_file)
相关推荐
weixin_3077791310 分钟前
Jenkins Pipeline 完全指南:核心概念、使用详解与最佳实践
开发语言·ci/cd·自动化·jenkins·etl
kk”12 分钟前
c++红黑树
开发语言·c++
Gomiko14 分钟前
JavaScript DOM 原生部分(二):元素内容修改
开发语言·javascript·ecmascript
Z_W_H_17 分钟前
【C#】C#中值类型和引用类型参数传递的区别
开发语言·c#
Data_agent23 分钟前
实战:用Splash搞定JavaScript密集型网页渲染
开发语言·javascript·ecmascript
leiming625 分钟前
C++ 02 函数模板案例
开发语言·c++·算法
weixin_4215850126 分钟前
PYTHON 迭代器1 - PEP-255
开发语言·python
小新11037 分钟前
vs2022+Qt插件初体验,创建带 UI 界面的 Qt 项目
开发语言·qt·ui
摘星编程44 分钟前
Ascend C编程语言详解:打造高效AI算子的利器
c语言·开发语言·人工智能
雨中飘荡的记忆1 小时前
Java面向对象编程详解
java·开发语言