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)
相关推荐
曹牧9 分钟前
Java:处理 HTTP 请求的 Content-Type
java·开发语言
AI技术增长10 分钟前
Pytorch图像去噪实战(八):Noise2Void盲点网络图像去噪实战,只有单张带噪图也能训练
人工智能·pytorch·python
才兄说15 分钟前
机器人二次开发机器狗巡检?路径覆盖率100%
python
隔壁大炮21 分钟前
Day07-RNN层(循环网络层)
人工智能·pytorch·python·rnn·深度学习·神经网络·计算机视觉
itzixiao22 分钟前
L1-066 猫是液体(5分)[java][python]
java·开发语言·python·算法
zhoutongsheng26 分钟前
如何解决ORA-01078参数文件错误_pfile与spfile互相创建恢复
jvm·数据库·python
Lightning-py29 分钟前
Python 配置日志(Logging)
开发语言·python
2401_8242226930 分钟前
HTML怎么标注字数限制提示_HTML实时字数统计占位【详解】
jvm·数据库·python
隔窗听雨眠34 分钟前
MySQL主从延迟根因诊断法
开发语言·php
Hui_AI72040 分钟前
基于RAG的农产品GEO溯源智能问答系统实现
开发语言·网络·人工智能·python·算法·创业创新