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)
相关推荐
xzlAwin12 小时前
Win10安装Go语言多版本管理器g工具
开发语言·golang
for_ever_love__12 小时前
python基础语法学习: 文件操作
python·学习
(initial)12 小时前
C-05. Kernel Fusion 代价边界:少写回 vs 寄存器压力与 occupancy
c语言·开发语言·cuda
青春不败 177-3266-052012 小时前
基于R、Python的Copula变量相关性分析及AI大模型应用
人工智能·python·r语言·贝叶斯·统计学·copula
汤姆yu13 小时前
基于python大数据的高校舆情监测系统的设计与实现
大数据·开发语言·python·分享·分析·舆情
Cory.眼13 小时前
Python爬虫实战:从入门到进阶
开发语言·爬虫·python
qq_5896660513 小时前
Java继承
java·开发语言
八角.。13 小时前
面向对象-多态
java·开发语言
qq_4221525713 小时前
Token到底是什么?Tokenizer分词机制与中文token开销入门科普
人工智能·python·深度学习
@卓越俊逸_角立杰出@13 小时前
快速学会 Java 实现意图识别:从规则匹配到 BiLSTM 分类器
java·开发语言·人工智能