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)
相关推荐
其实秋天的枫几秒前
【26年3月最新】计算机二级WPS真题试题及答案14套电子版PDF(含操作题和选择题)
经验分享·pdf
梦醒过后说珍重1 分钟前
Python 工程化实战:如何将复杂的EndoMamba感知损失封装为“即插即用”的独立模块包
python·深度学习
2501_945423543 分钟前
C++编译期多态实现
开发语言·c++·算法
2401_879693873 分钟前
设计模式在C++中的实现
开发语言·c++·算法
爱钓鱼的程序员小郭4 分钟前
阿里云自动配置安全组IP白名单
python·tcp/ip·安全·阿里云
程序员Ctrl喵5 分钟前
状态管理与响应式编程 —— 驾驭复杂应用的“灵魂工程”
开发语言·flutter·ui·架构
☆5666 分钟前
C++中的代理模式高级应用
开发语言·c++·算法
梦醒过后说珍重6 分钟前
PyTorch 工程实践:如何优雅地将 ViT 大模型封装为即插即用的感知损失(Perceptual Loss)
python·深度学习
2301_818419018 分钟前
编译器命令选项优化
开发语言·c++·算法
m0_518019488 分钟前
C++图形编程(OpenGL)
开发语言·c++·算法