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)
相关推荐
杨超越luckly2 分钟前
HTML应用指南:利用POST请求获取全国极氪门店位置信息
python·arcgis·html·数据可视化·门店数据
青春不败 177-3266-05202 分钟前
最新AI-Python机器学习与深度学习实践技术应用
人工智能·python·深度学习·机器学习·卷积神经网络·语义分割·自编码
三维鱼2 分钟前
Python组合数据类型----5.2列表( 5.2.4 )
python
零日失眠者3 分钟前
【系统监控系列】005:CPU温度监控脚本
后端·python
故事不长丨5 分钟前
解锁C#编程秘籍:封装、继承、多态深度剖析
开发语言·数据库·c#
远瞻。6 分钟前
【环境配置】快速转移conda上的python环境
开发语言·python·conda
上班职业摸鱼人7 分钟前
Python迭代器与生成器深度解析:吃透yield关键字,写出高效内存代码
python
缘三水10 分钟前
【C语言】5.printf和scanf(新手向详细版)
c语言·开发语言·基础语法
无敌最俊朗@11 分钟前
Qt处理tcp数据 粘包 拆包 的简单方法
开发语言
棒棒的皮皮11 分钟前
【OpenCV】Python图像处理之图像加法运算
图像处理·python·opencv·计算机视觉