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)
相关推荐
2301_795741799 分钟前
构建一个基于命令行的待办事项应用
jvm·数据库·python
星空下的月光影子11 分钟前
易语言开发从入门到精通:进阶篇·数据处理与分析自动化·高频刚需手工转自动场景全覆盖
开发语言
林夕sama12 分钟前
多线程基础(四)
java·开发语言
Yang-Never16 分钟前
ADB ->adb shell perfetto 抓取 trace 指令
android·开发语言·adb·android studio
小鸡吃米…20 分钟前
Python 网络爬虫 —— 环境设置
开发语言·爬虫·python
add45a30 分钟前
C++中的观察者模式
开发语言·c++·算法
sw12138931 分钟前
Python字典与集合:高效数据管理的艺术
jvm·数据库·python
进击的小头33 分钟前
第13篇:基于伯德图的超前_滞后校正器深度设计
python·算法
该怎么办呢40 分钟前
Source/Core/Event.js
开发语言·javascript·ecmascript·cesium