【源码阅读】多个函数抽象为类(实现各种类型文件转为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 可用性检查。
增加了各种状态检查
提取文件的后缀类型,并使用字典中对应的方法进行文件转换
支持批量转换
使用起来也很方便,先创建一个实例,然后调用实例
原文地址:https://blog.csdn.net/qq_43920838/article/details/146360200
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/592779.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.kler.cn/a/592779.html 如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!