目錄
- 一、原始函數
- 二、類
- 三、轉換過程
一、原始函數
最開始就是寫了幾個函數(包括doc、excel、ppt類型的文件)轉換為pdf,需要將這些函數形成一個類。相似的一類函數就可以組成一個實現特定功能的類
import subprocess
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPagesdef 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 Pathclass 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 Trueexcept (subprocess.CalledProcessError, FileNotFoundError):return Falsedef _convert_document(self, input_file: str) -> bool:"""轉換文檔文件(DOC、DOCX等)"""try:subprocess.run([self.libreoffice_path, '--headless', '--convert-to', 'pdf', input_file], check=True)return Trueexcept subprocess.CalledProcessError:return Falsedef _convert_excel(self, input_file: str) -> bool:"""轉換電子表格文件(XLS、XLSX等)"""try:subprocess.run([self.libreoffice_path, '--headless', '--convert-to', 'pdf', input_file], check=True)return Trueexcept subprocess.CalledProcessError:return Falsedef _convert_presentation(self, input_file: str) -> bool:"""轉換演示文稿文件(PPT、PPTX等)"""try:subprocess.run([self.libreoffice_path, '--headless', '--convert-to', 'pdf', input_file], check=True)return Trueexcept subprocess.CalledProcessError:return Falsedef 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 Falseinput_path = Path(input_file)if not input_path.exists():print(f"錯誤:輸入文件 {input_file} 不存在。")return Falsefile_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').nameprint(f"轉換成功:{output_file}")else:print(f"轉換失敗:{input_file}")return successdef 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 可用性檢查。
增加了各種狀態檢查
提取文件的后綴類型,并使用字典中對應的方法進行文件轉換
支持批量轉換
使用起來也很方便,先創建一個實例,然后調用實例