当前位置: 首页 > news >正文

【源码阅读】多个函数抽象为类(实现各种类型文件转为PDF)

目录

  • 一、原始函数
  • 二、类
  • 三、转换过程

一、原始函数


最开始就是写了几个函数(包括doc、excel、ppt类型的文件)转换为pdf,需要将这些函数形成一个类。相似的一类函数就可以组成一个实现特定功能的类

import subprocess
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

def doc_to_pdf(input_file):
    """
    将指定文件转换为 PDF 格式。

    该函数使用 LibreOffice 的命令行工具 lowriter 将输入文件转换为 PDF。
    支持多种文件格式,如 .docx, .doc, .odt 等。

    参数:
    input_file (str): 要转换的输入文件路径
    """
    try:
        # 调用命令行工具 lowriter 进行转换
        subprocess.run(["lowriter", "--convert-to", "pdf", input_file], check=True)
        print(f"文件 {input_file} 已成功转换为 PDF。")
    except subprocess.CalledProcessError as e:
        print(f"转换失败: {e}")
    except FileNotFoundError:
        print("未找到 lowriter 命令,请确保 LibreOffice 已安装。")


def excel_to_pdf(input_file):
    """
    将 Excel 文件转换为 PDF 格式。

    该函数使用 LibreOffice 的命令行工具将 Excel 文件转换为 PDF。

    参数:
    input_file (str): 要转换的 Excel 文件路径
    """
    try:
        # 调用命令行工具 libreoffice 进行转换
        subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", input_file], check=True)
        print(f"文件 {input_file} 已成功转换为 PDF。")
    except subprocess.CalledProcessError as e:
        print(f"转换失败: {e}")
    except FileNotFoundError:
        print("未找到 libreoffice 命令,请确保 LibreOffice 已安装。")


def ppt_to_pdf(input_file):
    """
    将 PPT 文件转换为 PDF 格式。

    该函数使用 LibreOffice 的命令行工具将 PPT 文件转换为 PDF。

    参数:
    input_file (str): 要转换的 PPT 文件路径
    """
    subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", input_file], check=True)
    print(f"文件 {input_file} 已成功转换为 PDF。")

if __name__ == '__main__':
    input_file='/data/hyq/code/llf/2024xx.xlsx'
    output_file='2024年xx.pdf'
    excel_to_pdf(input_file)

二、类


更加结构化的文件转化类

import subprocess
import os
from typing import Optional, List
from pathlib import Path

class DocumentToPDF:
    """文档转PDF转换器类
    
    支持将各种文档格式(Word、Excel、PPT等)转换为PDF格式。
    使用LibreOffice作为转换工具。
    """
    
    def __init__(self, libreoffice_path: Optional[str] = None):
        """
        初始化转换器
        
        Args:
            libreoffice_path: LibreOffice可执行文件的路径,默认为None(使用系统PATH中的LibreOffice)
        """
        self.libreoffice_path = libreoffice_path or 'libreoffice'
        self.supported_formats = {
            'doc': self._convert_document,
            'docx': self._convert_document,
            'xls': self._convert_excel,
            'xlsx': self._convert_excel,
            'ppt': self._convert_presentation,
            'pptx': self._convert_presentation,
            'odt': self._convert_document,
            'ods': self._convert_excel,
            'odp': self._convert_presentation
        }
    
    def _check_libreoffice(self) -> bool:
        """检查LibreOffice是否可用"""
        try:
            subprocess.run([self.libreoffice_path, '--version'], 
                         check=True, capture_output=True)
            return True
        except (subprocess.CalledProcessError, FileNotFoundError):
            return False
    
    def _convert_document(self, input_file: str) -> bool:
        """转换文档文件(DOC、DOCX等)"""
        try:
            subprocess.run([self.libreoffice_path, '--headless', 
                          '--convert-to', 'pdf', input_file], check=True)
            return True
        except subprocess.CalledProcessError:
            return False
    
    def _convert_excel(self, input_file: str) -> bool:
        """转换电子表格文件(XLS、XLSX等)"""
        try:
            subprocess.run([self.libreoffice_path, '--headless', 
                          '--convert-to', 'pdf', input_file], check=True)
            return True
        except subprocess.CalledProcessError:
            return False
    
    def _convert_presentation(self, input_file: str) -> bool:
        """转换演示文稿文件(PPT、PPTX等)"""
        try:
            subprocess.run([self.libreoffice_path, '--headless', 
                          '--convert-to', 'pdf', input_file], check=True)
            return True
        except subprocess.CalledProcessError:
            return False
    
    def convert(self, input_file: str, output_dir: Optional[str] = None) -> bool:
        """
        转换文件为PDF格式
        
        Args:
            input_file: 输入文件路径
            output_dir: 输出目录,默认为None(使用输入文件所在目录)
        
        Returns:
            bool: 转换是否成功
        """
        if not self._check_libreoffice():
            print("错误:未找到LibreOffice,请确保已正确安装。")
            return False
            
        input_path = Path(input_file)
        if not input_path.exists():
            print(f"错误:输入文件 {input_file} 不存在。")
            return False
            
        file_extension = input_path.suffix.lower()[1:]  # 移除点号
        if file_extension not in self.supported_formats:
            print(f"错误:不支持的文件格式 {file_extension}")
            return False
            
        # 如果指定了输出目录,确保它存在
        if output_dir:
            os.makedirs(output_dir, exist_ok=True)
            os.chdir(output_dir)
            
        # 执行转换
        convert_func = self.supported_formats[file_extension]
        success = convert_func(str(input_path))
        
        if success:
            output_file = input_path.with_suffix('.pdf').name
            print(f"转换成功:{output_file}")
        else:
            print(f"转换失败:{input_file}")
            
        return success
    
    def batch_convert(self, input_files: List[str], output_dir: Optional[str] = None) -> List[bool]:
        """
        批量转换文件
        
        Args:
            input_files: 输入文件路径列表
            output_dir: 输出目录
            
        Returns:
            List[bool]: 每个文件的转换结果
        """
        return [self.convert(f, output_dir) for f in input_files]


# 使用示例
if __name__ == '__main__':
    # 创建转换器实例
    converter = DocumentToPDF()
    
    # 单个文件转换
    input_file = '/data/hyq/code/llf/2024年技术能力群个人创值数据汇总.xlsx'
    converter.convert(input_file)
    
    # 批量转换示例
    # files = ['doc1.docx', 'sheet1.xlsx', 'ppt1.pptx']
    # converter.batch_convert(files, output_dir='output_pdfs')

三、转换过程


面向对象设计,意味着更好的代码组织和复用。整个类在下面函数的书写过程中,增加了错误处理和状态检查,使得类更加健壮和灵活,可以更好地处理各种情况和错误。增加了类型提示,提高代码可读性
首先是类的初始化,且定义了一个不同类型的文件如何进行处理的字典,支持更多文件格式。
在这里插入图片描述
增加了 LibreOffice 可用性检查。
在这里插入图片描述
增加了各种状态检查

在这里插入图片描述
提取文件的后缀类型,并使用字典中对应的方法进行文件转换
在这里插入图片描述
支持批量转换
在这里插入图片描述
使用起来也很方便,先创建一个实例,然后调用实例
在这里插入图片描述

相关文章:

  • UE4学习笔记 FPS游戏制作6 添加枪口特效
  • 详细解析GetOpenFileName()
  • Vue3 核心特性解析:Suspense 与 Teleport 原理深度剖析
  • 区块链技术驱动金融第一章 —— 走进区块链的基石:密码学与加密货币
  • 性能测试过程实时监控分析
  • 虚幻基础:动作系统3
  • 基于Arduino控制的温室蔬菜园环境监控系统(论文+源码)
  • python-56-基于Vue和Flask进行前后端分离的项目开发示例实战
  • FPGA学习(二)——基于DE2-115开发板的LED流水灯设计
  • 构建下一代AI Agent:自动化开发与行业落地全解析
  • SpringBoot3+Vue3实战(Vue3快速开发登录注册页面并对接后端接口)(4)
  • <table>内有两行<tr>,第一行设定高度为60,剩余第二行,和右侧元素高度补齐。
  • Linux 锁、线程同步
  • Elasticsearch text字段检索方法
  • 各种医学方面大模型总结——自用
  • 前端调试实战指南:从入门到高阶的完整解决方案
  • 【Triton 教程】triton_language.tensor
  • 【AVRCP】服务发现互操作性:CT 与 TG 的 SDP 协议契约解析
  • TDE透明加密技术:免改造实现华为云ECS中数据库和文件加密存储
  • Cool Request:可以统计任意方法耗时
  • wordpress 锚/google优化推广
  • 5151ppt网站建设/产品免费推广网站有哪些
  • wordpress缩略图代码/兰州快速seo整站优化招商
  • 网站被k后换域名 做301之外_之前发的外链怎么办/合肥seo搜索优化
  • 如何做网站联盟/班级优化大师是干什么用的
  • 坪山网站建设哪家公司靠谱/seo专业培训需要多久