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)
相关推荐
卖个几把萌2 分钟前
解决 Python 项目依赖冲突:使用 pip-tools 一键生成现代化的 requirements.txt
开发语言·python·pip
黎雁·泠崖5 分钟前
Java字符串入门:API入门+String类核心
java·开发语言·python
哈哈不让取名字24 分钟前
用Pygame开发你的第一个小游戏
jvm·数据库·python
程序员敲代码吗25 分钟前
Python异步编程入门:Asyncio库的使用
jvm·数据库·python
MediaTea25 分钟前
Python:MRO 解密 —— C3 线性化算法
java·开发语言
sunfove26 分钟前
Python小游戏:在 2048 游戏中实现基于线性插值(Lerp)的平滑动画
开发语言·python·游戏
2501_9445264231 分钟前
Flutter for OpenHarmony 万能游戏库App实战 - 抽牌游戏实现
android·开发语言·python·flutter·游戏
a程序小傲33 分钟前
听说前端又死了?
开发语言·前端·mysql·算法·postgresql·深度优先
副露のmagic34 分钟前
python基础复健
python·算法
学Linux的语莫42 分钟前
python项目打包为镜像
java·python·spring