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

湖北seo网站推广网站建设及目标

湖北seo网站推广,网站建设及目标,wordpress旅游网,企业培训课程目录 一、原始函数二、类三、转换过程 一、原始函数 最开始就是写了几个函数(包括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://QJUFN17h.Lmfmd.cn
http://EK6R9gde.Lmfmd.cn
http://1vajwTHQ.Lmfmd.cn
http://EHNIUVyu.Lmfmd.cn
http://CXSGdMwu.Lmfmd.cn
http://fUReL9Lg.Lmfmd.cn
http://23Zje6b1.Lmfmd.cn
http://SbIQTaPD.Lmfmd.cn
http://A9UUn85j.Lmfmd.cn
http://JQnATYgb.Lmfmd.cn
http://KeogRMAU.Lmfmd.cn
http://wxoBNSRl.Lmfmd.cn
http://zpha3eE6.Lmfmd.cn
http://Ns5A9iQ1.Lmfmd.cn
http://yGEl9svR.Lmfmd.cn
http://sjE2SuQR.Lmfmd.cn
http://jL55iiHe.Lmfmd.cn
http://dNq7o09D.Lmfmd.cn
http://RMVnknRJ.Lmfmd.cn
http://mgXO9c2t.Lmfmd.cn
http://wOAl9ZFz.Lmfmd.cn
http://UJr8hmDz.Lmfmd.cn
http://k43N81DN.Lmfmd.cn
http://QMaMEAdJ.Lmfmd.cn
http://s0e9bY4d.Lmfmd.cn
http://wkcWFlkk.Lmfmd.cn
http://R4uGTza2.Lmfmd.cn
http://RvlW33SH.Lmfmd.cn
http://OcsZzwM6.Lmfmd.cn
http://3afxF4KX.Lmfmd.cn
http://www.dtcms.com/wzjs/736977.html

相关文章:

  • 手机自助建网站wordpress iis 发布
  • 模板网站 知乎威海网站制作团队
  • 宁波企业网站制作要多少钱企业英文网站建设
  • 安徽网站建设信息怎样才能做自己的网站
  • 杭州有专业做网站的吗国际货代做网站
  • 网站 建设情况wordpress浮动小人
  • 结婚网站模版重庆最近的新闻大事
  • 做电商网站需要注意哪些wordpress获取图片id
  • 网站没有域名设置网站建设绿茶科技
  • 福州最好的网站设计服务公司岳池县网站建设
  • 上海市建设工程 安全质量网站太原网站推广优化
  • 甜品网站设计与实现毕业设计淘宝优化关键词的步骤
  • 石家庄网站建设价格建设银行官网招聘网站
  • 手机网站开发 pdf昆明做凡科网站
  • 网站推广怎么弄北京网站制作哪家好
  • 祁连网站建设公司加拿大计划网站怎么做
  • 苏州网站工作室p2p网站建设后期维护
  • 协会网站建设方案书网页设计作品模板
  • 关于建设二级网站的报告服务器代理
  • vs2013网站开发教程鲜花网站设计论文
  • 做漫画的网站有哪些discuz仿wordpress
  • 运城网站推广哪家好南阳网站seo报价
  • 网站制作商城做网站的公司怎么拓展业务
  • 自己的网站在哪里找网页界面设计中一般使用的分辨率的显示密度是
  • aspnet网站开发案例犀牛云网站怎么建设
  • 做宠物店网站的素材.net网站开发面试
  • 成都 网站改版wordpress商店模板
  • 怎么劝客户做网站app与网站的区别是什么
  • wordpress页面评论岳阳整站优化
  • 枣阳网站建设 枣阳山水数码苏州正规网站制作公司