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)
相关推荐
蚊子码农7 分钟前
算法题解记录-2452距离字典两次编辑以内的单词
开发语言·算法·c#
wangbing11258 分钟前
Java构造函数不能加void
java·开发语言
Never_Satisfied9 分钟前
在JavaScript / HTML中,数组查找第一个符合要求元素
开发语言·javascript·html
嵌入式×边缘AI:打怪升级日志19 分钟前
9.2.1 分析 Write File Record 功能(保姆级讲解)
java·开发语言·网络
橙露20 分钟前
Python 异步爬虫进阶:协程 + 代理池高效爬取实战
开发语言·爬虫·python
kylezhao20191 小时前
C#异步和并发在IO密集场景的典型应用 async/await
开发语言·数据库·c#
m0_531237171 小时前
C语言-函数练习2
c语言·开发语言
锅包一切1 小时前
在蓝桥杯边练边学Rust:2.原生类型
开发语言·学习·蓝桥杯·rust
lightqjx1 小时前
【C++】C++11 常见特性
开发语言·c++·c++11
一切尽在,你来1 小时前
AI 大模型应用开发前置知识:Python 泛型编程全教程
开发语言·人工智能·python·ai编程