Python实现Word、Excel、PPT批量转为PDF

这篇具有很好参考价值的文章主要介绍了Python实现Word、Excel、PPT批量转为PDF。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

今天看见了一个有意思的脚本Python批量实现Word、EXCLE、PPT转PDF文件。

因为我平时word用的比较的多,所以深有体会,具体怎么实现的我们就不讨论了,因为这个去学了也没什么提升,不然也不会当作脚本了。这里我将其放入了pyzjr库中,也方便大家进行调用。

你可以去下载pyzjr:

pip install pyzjr -i https://pypi.tuna.tsinghua.edu.cn/simple

调用方法:

import pyzjr as pz

# 实例化对象
Mpdf = pz.Microsoft2PDF()
# 调用类的方法
Mpdf.Word2Pdf()  # word -> pdf
Mpdf.Excel2Pdf()  # excel -> pdf
Mpdf.PPt2Pdf()  # ppt -> pdf
Mpdf.WEP2Pdf()  # word,excel,ppt -> pdf

上面就是api的调用了,统一会将文件存放在目标文件夹下新建的名为pdf文件夹中。

pyzjr中的源码:

import win32com.client, gc, os

class Microsoft2PDF():
    """Convert Microsoft Office documents (Word, Excel, PowerPoint) to PDF format"""
    def __init__(self,filePath = ""):
        """
        :param filePath: 如果默认是空字符,就默认当前路径
        """
        self.flagW = self.flagE = self.flagP = 1
        self.words = []
        self.ppts = []
        self.excels = []

        if filePath == "":
            filePath = os.getcwd()
        folder = filePath + '\\pdf\\'
        self.folder = CreateFolder(folder,debug=False)

        self.filePath = filePath
        for i in os.listdir(self.filePath):
            if i.endswith(('.doc', 'docx')):
                self.words.append(i)
            if i.endswith(('.ppt', 'pptx')):
                self.ppts.append(i)
            if i.endswith(('.xls', 'xlsx')):
                self.excels.append(i)

        if len(self.words) < 1:
            print("\n[pyzjr]:No Word files\n")
            self.flagW = 0
        if len(self.ppts) < 1:
            print("\n[pyzjr]:No PPT file\n")
            self.flagE = 0
        if len(self.excels) < 1:
            print("\n[pyzjr]:No Excel file\n")
            self.flagP = 0

    def Word2Pdf(self):
        if self.flagW == 0:
            return 0
        else:
            print("\n[Start Word ->PDF conversion]")
            try:
                print("Open Word Process...")
                word = win32com.client.Dispatch("Word.Application")
                word.Visible = 0
                word.DisplayAlerts = False
                doc = None
                for i in range(len(self.words)):
                    print(i)
                    fileName = self.words[i]  # file name
                    fromFile = os.path.join(self.filePath, fileName)  # file address
                    toFileName = self.changeSufix2Pdf(fileName)  # Generated file name
                    toFile = self.toFileJoin(toFileName)  # Generated file address

                    print("Conversion:" + fileName + "in files...")
                    try:
                        doc = word.Documents.Open(fromFile)
                        doc.SaveAs(toFile, 17)
                        print("Convert to:" + toFileName + "file completion")
                    except Exception as e:
                        print(e)

                print("All Word files have been printed")
                print("End Word Process...\n")
                doc.Close()
                doc = None
                word.Quit()
                word = None
            except Exception as e:
                print(e)
            finally:
                gc.collect()

    def Excel2Pdf(self):
        if self.flagE == 0:
            return 0
        else:
            print("\n[Start Excel -> PDF conversion]")
            try:
                print("open Excel Process...")
                excel = win32com.client.Dispatch("Excel.Application")
                excel.Visible = 0
                excel.DisplayAlerts = False
                wb = None
                ws = None
                for i in range(len(self.excels)):
                    print(i)
                    fileName = self.excels[i]
                    fromFile = os.path.join(self.filePath, fileName)

                    print("Conversion:" + fileName + "in files...")
                    try:
                        wb = excel.Workbooks.Open(fromFile)
                        for j in range(wb.Worksheets.Count):  # Number of worksheets, one workbook may have multiple worksheets
                            toFileName = self.addWorksheetsOrder(fileName, j + 1)
                            toFile = self.toFileJoin(toFileName)

                            ws = wb.Worksheets(j + 1)
                            ws.ExportAsFixedFormat(0, toFile)
                            print("Convert to:" + toFileName + "file completion")
                    except Exception as e:
                        print(e)
                # 关闭 Excel 进程
                print("All Excel files have been printed")
                print("Ending Excel process...\n")
                ws = None
                wb.Close()
                wb = None
                excel.Quit()
                excel = None
            except Exception as e:
                print(e)
            finally:
                gc.collect()

    def PPt2Pdf(self):
        if self.flagP == 0:
            return 0
        else:
            print("\n[Start PPT ->PDF conversion]")
            try:
                print("Opening PowerPoint process...")
                powerpoint = win32com.client.Dispatch("PowerPoint.Application")
                ppt = None
                for i in range(len(self.ppts)):
                    print(i)
                    fileName = self.ppts[i]
                    fromFile = os.path.join(self.filePath, fileName)
                    toFileName = self.changeSufix2Pdf(fileName)
                    toFile = self.toFileJoin(toFileName)

                    print("Conversion:" + fileName + "in files...")
                    try:
                        ppt = powerpoint.Presentations.Open(fromFile, WithWindow=False)
                        if ppt.Slides.Count > 0:
                            ppt.SaveAs(toFile, 32)
                            print("Convert to:" + toFileName + "file completion")
                        else:
                            print("Error, unexpected: This file is empty, skipping this file")
                    except Exception as e:
                        print(e)
                print("All PPT files have been printed")
                print("Ending PowerPoint process...\n")
                ppt.Close()
                ppt = None
                powerpoint.Quit()
                powerpoint = None
            except Exception as e:
                print(e)
            finally:
                gc.collect()

    def WEP2Pdf(self):
        """
        Word, Excel and PPt are all converted to PDF.
        If there are many files, it may take some time
        """
        print("Convert Microsoft Three Musketeers to PDF")
        self.Word2Pdf()
        self.Excel2Pdf()
        self.PPt2Pdf()
        print(f"All files have been converted, you can find them in the {self.folder}")

    def changeSufix2Pdf(self,file):
        """将文件后缀更改为.pdf"""
        return file[:file.rfind('.')] + ".pdf"

    def addWorksheetsOrder(self,file, i):
        """在文件名中添加工作表顺序"""
        return file[:file.rfind('.')] + "_worksheet" + str(i) + ".pdf"

    def toFileJoin(self, file):
        """将文件路径和文件名连接为完整的文件路径"""
        return os.path.join(self.filePath, 'pdf', file[:file.rfind('.')] + ".pdf")

 这里我对原先博主的代码进行了一定的优化,使其可供我们调用。

Python实现Word、Excel、PPT批量转为PDF,# 优质教程,# Python代码,powerpoint,pdf

这是控制台打印出来的信息,我们可以发现在调用WEP2Pdf时,如果当前文件夹中没有word的文件也能继续去转换。 文章来源地址https://www.toymoban.com/news/detail-694695.html

到了这里,关于Python实现Word、Excel、PPT批量转为PDF的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • Python - 读取pdf、word、excel、ppt、csv、txt文件提取所有文本

    本文对使用python读取pdf、word、excel、ppt、csv、txt等常用文件,并提取所有文本的方法进行分享和使用总结。 可以读取不同文件的库和方法当然不止下面分享的这些,本文的代码主要目标都是:方便提取文件中所有文本的实现方式。 这些库的更多使用方法,请到官方文档中查

    2024年02月13日
    浏览(263)
  • python 批量修改文件名(PDF、word、Excel、图片、视频等)

    python 批量修改文件名(PDF、word、Excel、图片、视频等)

          很多朋友遇到批量修改文件名的问题,网上各种搜,操作麻烦不说还有些需要付费。这里不多废话,直接上代码。 一、支持库 二、 定义函数 三、程序入口 四、运行,微云 下载:文件分享

    2024年01月23日
    浏览(46)
  • 文档在线预览(四)将word、txt、ppt、excel、图片转成pdf来实现在线预览

    文档在线预览(四)将word、txt、ppt、excel、图片转成pdf来实现在线预览

    @ 目录 事前准备 1、需要的maven依赖 添加spire依赖(商用,有免费版,但是存在页数和字数限制,不采用spire方式可不添加) 2、后面用到的工具类代码: 一、word文件转pdf文件(支持doc、docx) 1、使用aspose方式 2、使用poi方式 3、使用spire方式 二、txt文件转pdf文件 三、PPT文件转

    2024年02月08日
    浏览(36)
  • 【Vue实用功能】Vue实现文档在线预览功能,在线预览PDF、Word、Excel、ppt等office文件

    【Vue实用功能】Vue实现文档在线预览功能,在线预览PDF、Word、Excel、ppt等office文件

    Luckysheet 是一个类似于 excel 的在线电子表格,功能强大、配置简单且完全开源。 安装 Luckysheet 1、通过CDN引入依赖 由于 Luckysheet 现在还没有发布出模块化的开发,不能使用 npm,所以我们需要在 VUE 项目中手动引入相关文件。编辑 public/index.html 文件,在里面添加如下代码 2、指

    2023年04月22日
    浏览(130)
  • Android 应用内打开Word、Excel、PPT、PDF等文档

    Android 应用内打开Word、Excel、PPT、PDF等文档

    Android平台中,可以使用以下几种方式打开Word和Excel文档: 预览图: 一:直接上传给第三方之后用webview打开         1、微软:         https://view.officeapps.live.com/op/view.aspx?src=文件链接         2、XDOC文档预览服务         http://www.xdocin.com/xdoc?_func=to_format=html_cache=tru

    2024年02月16日
    浏览(8)
  • 微信小程序查看word,excel,ppt以及pdf文件(文档)

    微信小程序查看word,excel,ppt以及pdf文件(文档)

     博主介绍: 本人专注于Android/java/数据库/微信小程序技术领域的开发,以及有好几年的计算机毕业设计方面的实战开发经验和技术积累;尤其是在安卓(Android)的app的开发和微信小程序的开发,很是熟悉和了解;本人也是多年的Android开发人员;希望我发布的此篇文件可以帮

    2024年02月07日
    浏览(69)
  • 前端(vue)js在线预览PDF、Word、Excel、ppt等office文件

    可选参数 pdf=true,word文档尝试以pdf方式显示,默认false watermark=水印文本,显示文本水印;“img:”+图片url表示图片水印,如:img:https://view.xdocin.com/demo/wm.png saveable=true,是否允许保存源文件,默认false printable=false,是否允许打印,默认true ©able=false,是否允许选择复制内容,

    2024年02月13日
    浏览(42)
  • 在java中如何使用openOffice进行格式转换,word,excel,ppt,pdf互相转换

    在java中如何使用openOffice进行格式转换,word,excel,ppt,pdf互相转换

    1.首先需要下载并安装openOffice,下载地址为: Apache OpenOffice download | SourceForge.net 2.安装后,可以测试下是否可用; 3.build.gradle中引入依赖: 4.创建工具类,启动openOffice服务的方法 5.结束openOffice服务的方法 7.在测试方法中进行格式转换,如,他可以是任意类型转换,如excel转换

    2024年02月14日
    浏览(12)
  • 【工具插件类教学】Unity通过Aspose读取并显示打开PDF,PPT,Excel,Word

    目录 一、获取Aspose支持.Net的DLL 二、导入Unity的Plugin文件夹 三、分别编写四种文件的读取显示

    2024年02月02日
    浏览(42)
  • 如何利用python将pdf文档转为word?

    1.前言 有些时候,我们需要将pdf文档转换为word文档进行处理,但市面上的一些pdf软件往往需要付费才能使用。那么作为一名技术人员,如何才能实现pdf转word自由? 2.准备工作 提前安装好python的环境,并且安装对应的第三方包: 3.实现方法 3.1 convert方法 3.2 parse方法 3.3 仅转换其

    2024年02月13日
    浏览(14)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包