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)
相关推荐
froginwe1110 分钟前
R 基础运算
开发语言
醉城夜风~10 分钟前
[数据结构]堆详解
开发语言·数据结构
m0_7482522331 分钟前
Python 入门教程(2)搭建环境 2.4、VSCode配置Node.js运行环境
vscode·python·node.js
17´37 分钟前
Qt从入门到入土(八) -打包Qt程序
开发语言·c++·qt
Nine eight seven four37 分钟前
pdf修改内容:分享5款好用的工具
pdf
AI+程序员在路上38 分钟前
QT显示网页控件QAxWidget、QWebEngineView及区别
开发语言·qt
南玖yy43 分钟前
C语言柔性数组深度解析:动态内存管理的艺术
c语言·开发语言·柔性数组
梓羽玩Python1 小时前
太牛了!OWL:Manus 最强开源复现,开源框架GAIA基准测试中排第一!
人工智能·python
2301_764441331 小时前
python实现的生态模拟系统
开发语言·python·pygame
无世世1 小时前
【Java从入门到起飞】面向对象编程(高级)
java·开发语言