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)
相关推荐
dFObBIMmai2 分钟前
Go语言怎么用GitHub Actions_Go语言GitHub Actions教程【基础】
jvm·数据库·python
老鱼说AI3 分钟前
现代 LangChain 开发指南:从 LCEL 原理到企业级 RAG 与 Agent 实战
java·开发语言·人工智能·深度学习·神经网络·算法·机器学习
Michelle80233 分钟前
25大数据 11-1 函数
开发语言·python
aini_lovee10 分钟前
C#与倍福PLC(通过ADS协议)通信上位机源程序实现
开发语言·c#
dFObBIMmai11 分钟前
SQL复杂数据聚合_嵌套子查询与GROUP BY配合
jvm·数据库·python
fie888914 分钟前
基于 MATLAB 的前景背景分割系统
开发语言·matlab
小许同学记录成长22 分钟前
基于幅度形态与参数聚类的工作模式判别
python·算法·scikit-learn
郝学胜-神的一滴23 分钟前
Qt 入门 01-02: 开发环境搭建指南
开发语言·c++·qt·客户端
dinglu1030DL28 分钟前
CSS Grid布局如何实现网格项目排序_使用order属性改变显示顺序
jvm·数据库·python
财经资讯数据_灵砚智能33 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年5月13日
大数据·人工智能·python·信息可视化·自然语言处理