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 分钟前
编译与链接的本质:段(Section)的生成与定位
java·linux·开发语言
Ai财富密码22 分钟前
AI生成大屏可视化:数据智能驱动下的高维洞察与决策中枢
开发语言·人工智能·python·sdd
半兽先生25 分钟前
01阶段:大模型语言入门
开发语言·python
fengenrong26 分钟前
20260325
开发语言·c++
l1t29 分钟前
执行python pyperformance基准测试的步骤
开发语言·python
chushiyunen29 分钟前
python中的for循环、dict、set、列表、数组等
开发语言·python
IT 行者35 分钟前
实战LangChain4j集成MCP Server:让Java AI应用具备工具调用能力
java·开发语言·人工智能
sqyno1sky41 分钟前
数据分析与科学计算
jvm·数据库·python
always_TT41 分钟前
C语言中的“副作用”是什么?
c语言·开发语言
Sirius.z44 分钟前
第T10周:数据增强
python