Python实现批量word文档转pdf并统计其页码

作者:逃逸的卡路里 时间:2023-08-19 13:29:40 

pypdf2是一个Python模块,可以用来读取、写入和操作PDF文件。要安装pypdf2模块,请按照以下步骤操作:

确保你已经安装了Python。你可以在终端或命令提示符中输入python --version来检查Python是否已安装。

pypdf2模块的安装:

ModuleNotFoundError: No module named ‘PyPDF2’

Python实现批量word文档转pdf并统计其页码

安装完成后,你可以在Python中使用pypdf2模块来读取、写入和操作PDF文件。

例如,要读取一个PDF文件中的文本内容,你可以在Python脚本中导入pypdf2模块,然后使用PdfFileReader类读取文件并遍历每个页面。下面是一个简单的示例代码:

import pypdf2  

pdf_file = pypdf2.PdfFileReader('example.pdf')  
for page_num in range(pdf_file.getNumPages()):  
   page = pdf_file.getPage(page_num)  
   print(page.extractText())

这将打印出PDF文件中的每个页面的文本内容。

注意:

因PyPDF2 版本更新原因,一些类和函数已经过时,想要采用替代函数,例如获取pdf 页数 getNumPages 替换为直接使用 len(reader.pages)。

下面是两个报错的提示,把函数替换掉就行

PyPDF2.errors.DeprecationError: PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead.

PyPDF2.errors.DeprecationError: reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead.

Python实现批量word文档转pdf并统计其页码

利用Python代码实现批量word文档转换成PDF格式

并对转换的文档,进行页码统计,如下(代码示例)

# -*- coding:utf-8 -*-
import os  # 导入系统功能模块
from win32com.client import Dispatch, DispatchEx  # 导入pywin32模块的client包下的函数
from win32com.client import constants  #  导入pywin32模块的client包下的保存COM常量的类
from win32com.client import gencache    #  导入pywin32模块的client包下的gencache函数
from PyPDF2 import  PdfReader  # 获取页码用
import re  # 导入正则表达式模块

import pythoncom  # 导入封装了OLE自动化API的模块,该模块为pywin32的子模块

'''获取指定目录下的文件
  filepath:要遍历的目录
  filelist_out:输出文件列表
  file_ext:文件的扩展名,默认为任何类型的文件
'''
def getfilenames(filepath='',filelist_out=[],file_ext='all'):
   # 遍历filepath下的所有文件,包括子目录下的文件
   for fpath, dirs, fs in os.walk(filepath):
       for f in fs:
           fi_d = os.path.join(fpath, f)
           if file_ext == '.doc':  # 遍历Word文档文件
               if os.path.splitext(fi_d)[1] in ['.doc','.docx']:   # 判断是否为Word文件
                   filelist_out.append(re.sub(r'\\','/',fi_d))  # 添加到路径列表中
           else:
               if  file_ext == 'all':  # 要获取所有文件的情况
                   filelist_out.append(fi_d)  # 将文件路径添加到路径列表中
               elif os.path.splitext(fi_d)[1] == file_ext:  # 要获取除了Wrod文件以外的文件
                   filelist_out.append(fi_d)  # 将文件路径添加到路径列表中
               else:
                   pass
       filelist_out.sort()  # 对路径进行排序
   return filelist_out  # 返回文件完整路径列表

# Word转换为PDF(多个文件)
def wordtopdf(filelist,targetpath):
   totalPages = 0   # 记录总页码
   valueList = []
   try:
       pythoncom.CoInitialize()   # 调用线程初始化COM库,解决调用Word 2007时出现“尚未调用CoInitialize”错误的问题
       gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
       # 开始转换
       w = Dispatch("Word.Application")
       for fullfilename in filelist:
           (filepath,filename) = os.path.split(fullfilename)  # 分割文件路径和文件名,其中,filepath表示文件路径;filename表示文件名
           softfilename = os.path.splitext(filename)  # 分割文件名和扩展名
           os.chdir(filepath)  
           doc = os.path.abspath(filename)
           os.chdir(targetpath)
           pdfname = softfilename[0] + ".pdf"
           output = os.path.abspath(pdfname)
           pdf_name = output

# 文档路径需要为绝对路径,因为Word启动后当前路径不是调用脚本时的当前路径。
           try: # 捕捉异常
               doc = w.Documents.Open(doc, ReadOnly=1)
               doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF, \
                                       Item=constants.wdExportDocumentWithMarkup,
                                       CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
           except Exception as e: # 处理异常
               print(e)
           if os.path.isfile(pdf_name): # 判断文件是否存在
               # 获取页码
               pages = getPdfPageNum(pdf_name)   # 获取页码
               valueList.append([fullfilename,str(pages)])
               totalPages += pages  # 累加页码
               # os.remove(pdf_name)  # 删除生成的PDF文件
           else:
               print('转换失败!')
               return False
       w.Quit(constants.wdDoNotSaveChanges) # 退出Word应用程序
       return totalPages,valueList  # 返回总页码和每个文档的页码
   except TypeError as e:
       print('出错了!')
       print(e)
       return False
'''
功能:统计文档页码
path:文件绝对路径
'''
def getPdfPageNum(path):
   with open(path, "rb") as file:
       doc = PdfReader(file)
       pagecount = len(doc.pages)
   return pagecount

if __name__ == '__main__':
   sourcepath = r"C:/Users/Lenovo/Desktop/python代码示例/word/"  # 指定源路径(Word文档所在路径)
   targetpath = r"C:/Users/Lenovo/Desktop/python代码示例/pdf/"  # 指定目标路径(PDF保存路径)
   filelist = getfilenames(sourcepath,[],'.doc')  # 获取Word文档路径
   valueList = wordtopdf(filelist,targetpath)  # 实现将Word文档批量转换为PDF
   resultList = valueList[1]  # 获取统计结果
   if valueList:
       for i in resultList:
           print(i[0],i[1])
       totalPages = str(valueList[0]) # 总页数
       print("合计页数:",totalPages)
   else:
       print("没有要统计的文件或者统计失败!")

Python实现批量word文档转pdf并统计其页码

来源:https://blog.csdn.net/u014740628/article/details/130885683

标签:Python,word,pdf
0
投稿

猜你喜欢

  • Pandas实现聚合运算agg()的示例代码

    2023-09-27 12:35:49
  • python中wx将图标显示在右下角的脚本代码

    2022-10-27 02:26:53
  • 创建数据表/创建列的一些asp函数

    2008-06-24 12:21:00
  • Python连接数据库使用matplotlib画柱形图

    2024-01-21 19:02:49
  • Python使用numpy模块实现矩阵和列表的连接操作方法

    2023-02-17 21:05:41
  • 为什么str(float)在Python 3中比Python 2返回更多的数字

    2022-11-09 22:55:56
  • python 爬取吉首大学网站成绩单

    2023-08-02 05:57:13
  • vue-cli3项目升级到vue-cli4 的方法总结

    2024-04-27 15:48:50
  • SQL高级应用之使用SQL查询Excel表格数据的方法

    2024-01-23 09:24:39
  • Python3读写Excel文件(使用xlrd,xlsxwriter,openpyxl3种方式读写实例与优劣)

    2022-10-10 18:17:38
  • Python排序搜索基本算法之归并排序实例分析

    2023-10-19 04:15:11
  • js调用flash代码

    2010-01-23 12:35:00
  • python测试开发django之使用supervisord 后台启动celery 服务(worker/beat)

    2023-10-14 05:55:53
  • JavaScript对象的创建模式与继承模式示例讲解

    2024-04-23 09:27:40
  • python使用selenium模拟浏览器进入好友QQ空间留言功能

    2021-06-24 16:24:16
  • phpword插件导出word文件时中文乱码问题处理方案

    2024-05-13 09:24:03
  • python pandas库的安装和创建

    2023-09-25 22:49:02
  • vue3.0如何使用computed来获取vuex里数据

    2024-04-28 09:24:20
  • 用python实现学生信息管理系统

    2023-06-07 10:17:37
  • 对python dataframe逻辑取值的方法详解

    2021-08-23 03:09:38
  • asp之家 网络编程 m.aspxhome.com