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)
相关推荐
Forever_Hopeful5 分钟前
【C 语言生成指定范围随机数(整数 + 小数):原理、实现与避坑指南】
服务器·c语言·开发语言
午夜游鱼17 分钟前
Go 泛型实战:一行代码封装 sync.Pool,性能与安全兼得
开发语言·安全·golang
xchenhao28 分钟前
SciKit-Learn 全面分析 digits 手写数据集
python·机器学习·分类·数据集·scikit-learn·svm·手写
胡耀超38 分钟前
7、Matplotlib、Seaborn、Plotly数据可视化与探索性分析(探索性数据分析(EDA)方法论)
python·信息可视化·plotly·数据挖掘·数据分析·matplotlib·seaborn
索迪迈科技1 小时前
STL库——map/set(类函数学习)
开发语言·c++·学习
tangweiguo030519871 小时前
Django REST Framework 构建安卓应用后端API:从开发到部署的完整实战指南
服务器·后端·python·django
Dfreedom.1 小时前
在Windows上搭建GPU版本PyTorch运行环境的详细步骤
c++·人工智能·pytorch·python·深度学习
ForteScarlet1 小时前
Kotlin 2.2.20 现已发布!下个版本的特性抢先看!
android·开发语言·kotlin·jetbrains
兴科Sinco1 小时前
[leetcode 1]给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数[力扣]
python·算法·leetcode
anlogic1 小时前
Java基础 9.10
java·开发语言·算法