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

深圳网站建设学校web免费网站

深圳网站建设学校,web免费网站,石家庄做网站哪家好,东莞技术支持网站建设专家目录 一、原始函数二、类三、转换过程 一、原始函数 最开始就是写了几个函数(包括doc、excel、ppt类型的文件)转换为pdf,需要将这些函数形成一个类。相似的一类函数就可以组成一个实现特定功能的类 import subprocess import pandas as pd i…

目录

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

一、原始函数


最开始就是写了几个函数(包括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 可用性检查。
在这里插入图片描述
增加了各种状态检查

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

http://www.dtcms.com/wzjs/381539.html

相关文章:

  • 做装修的网站有哪些网站制作多少钱一个
  • 从seo角度谈网站建设佛山做网站的公司哪家好
  • 网站怎么做优化百度能搜索到seo网站优化培
  • wordpress隐藏下载插件上海seo推广公司
  • 视频链接怎么wordpress一键优化软件
  • 天津做网站优化价格搜索词热度查询
  • 南京定制网站建设怎么收费关键词查询
  • 用wordpress改seo推广骗局
  • 新疆生产建设兵团供销社网站app营销十大成功案例
  • 网站建设入门到精通武汉seo和网络推广
  • 常见的网站建设技术行者seo无敌
  • 三河市建设厅公示网站seo的关键词无需
  • 新媒体运营哪个培训机构好河南seo优化
  • 花钱也可以哪些网站可以做推广广告爱论坛
  • 网站建设公司是干嘛的今日国内新闻头条15条
  • 成功网站管理系统seo排名查询工具
  • 网站支付界面怎么做今日国内新闻大事件
  • 品牌网站建设 意义推广接单平台
  • 求一个全部用div做的网站成都seo优化排名推广
  • 济南网站建设bajiujiu广告竞价推广
  • 网站建设详细设计站长工具的使用seo综合查询运营
  • 网站开发设计师网站收录登录入口
  • 资讯是做网站还是公众号域名解析在线查询
  • 网站建设编程时注意事项谷歌seo站内优化
  • 中山企业网站推广公司网络营销软件代理
  • 专业做网站的顺德公司电子商务网站推广策略
  • 做期货看什么网站的资讯比较好的网站建设网站
  • wordpress 新闻模版搜索引擎优化 简历
  • 建网站用哪个好百度新闻
  • 漯河网站建设服务公司推广策划书模板范文