吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 901|回复: 8
收起左侧

[Python 原创] 统计文件夹中pdf和word文件的页数

[复制链接]
xiaoxinyu 发表于 2024-4-2 17:07
打字复印发送来的压缩包,一堆文件,全部打印后,要统计打印了多少张,于是有了这个,
代码写的很烂。
需要安装  PyPDF2   pywin32   tkinterdnd2库
[Python] 纯文本查看 复制代码
import os
import tkinter as tk
from tkinterdnd2 import TkinterDnD, DND_FILES

import os
import PyPDF2

import win32com.client

def clean_path(path):
    path=path.replace("/", "\\")
    # 去除路径中的花括号

    return path.strip('{}')

def on_drop(event):
    file_path = event.data
    print(file_path)
    file_path =clean_path(file_path)
    if os.path.isfile(file_path):
        #print("这是文件")
        ggg(file_path)
        result_label.config(text=txt1)


    elif os.path.isdir(file_path):
        #print("这是文件夹")
        button.config(state="normal")
        count_pdf_pages(file_path)
        result_label.config(text=txt)
    else:
        result_label.config(text=txt1 )



def ggg(file_path):
    global txt1
    txt1=""
    if file_path.endswith('.pdf'):
        with open(file_path, 'rb') as f:
            pdf_reader = PyPDF2.PdfFileReader(f)
            pdf_filename = os.path.split(file_path)[1]
            info = pdf_reader.numPages
            txt1=pdf_filename+"   "+str(info) + "页"
    elif file_path.endswith(".doc") or file_path.endswith(".docx"):

        try:
            word_app = win32com.client.Dispatch("Word.Application")
            word_app.Visible = False  # 防止弹出 Word 窗口
            doc = word_app.Documents.Open(file_path)
            word_filename = os.path.split(file_path)[1]
            txt1=word_filename+ "   "+str(doc.ComputeStatistics(2)) + "页"
            # pdf_pages += doc.ComputeStatistics(2)  # 2表示计算总页数
            doc.Close()
            word_app.Quit()
        except Exception as e:
            print(f"Error processing {file_path}: {e}")
    else:
        txt1="不是pdf或word格式的文件"

def count_pdf_pages(folder_path):
    pdf_pages = 0
    word_pages = 0
    global  pdf_list
    global word_list
    global error_list
    pdf_list=[]
    word_list=[]
    error_list=[]
    word_app = win32com.client.Dispatch("Word.Application")
    word_app.Visible = False
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.pdf'):
                file_path = os.path.join(folder_path, file)
                with open(file_path, 'rb') as f:
                    pdf_reader = PyPDF2.PdfFileReader(f)
                    pdf_filename = os.path.split(file)[1]
                    info = pdf_reader.numPages
                   # print(pdf_filename, str(info) + "页")
                    pdf_list.append(pdf_filename+"  "+str(info) + "页")

                    pdf_pages += pdf_reader.numPages
            elif file.endswith(".doc") or file.endswith(".docx"):
                file_path = os.path.join(root, file)
                try:
                    doc = word_app.Documents.Open(file_path)
                    word_filename = os.path.split(file)[1]
                    #print(word_filename, str(doc.ComputeStatistics(2)) + "页")
                    word_list.append(word_filename+"  "+str(doc.ComputeStatistics(2)) + "页")
                    word_pages += doc.ComputeStatistics(2)  # 2表示计算总页数
                    doc.Close()
                except Exception as e:
                    error_list.append(file_path+"发生意外,未纳入统计,请见谅")
                    # print(f"Error processing {file_path}: {e}")
            else:
                pass

    word_app.Quit()
    global txt
    txt=f'PDF文件个数为:{len(pdf_list)},总页数为:{pdf_pages}'+"\n" + f"Word文件个数为:{len(word_list)},总页数为:{word_pages}"+"\n"+f"合计总页数为:{word_pages+pdf_pages}"
    return txt
# folder_path = os.getcwd()  # 请替换为实际文件夹路径
#
# print(count_pdf_pages(folder_path))


# 创建主窗口
root = TkinterDnD.Tk()
root.title("统计pdf和word文件页数")

# 获取屏幕宽度和高度
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# 设置窗口宽度和高度为屏幕的30%和20%
window_width = int(screen_width * 0.2)
window_height = int(screen_height * 0.15)

# 将窗口居中显示
x_position = (screen_width - window_width) // 2
y_position = (screen_height - window_height) // 2

# 设置窗口大小和位置
root.geometry(f"{window_width}x{window_height}+{x_position}+{y_position}")

# 创建标签用于显示文件大小
result_label = tk.Label(root, text="拖入带有文件格式是pdf、doc、docx的文件或文件夹", pady=10)
result_label.pack(expand=True, fill="both")
# result_label.pack()

# 设置窗口拖拽功能
root.drop_target_register(DND_FILES)
root.dnd_bind('<<Drop>>', on_drop)


def open_new_window():
    new_window = tk.Toplevel(root)
    new_window.title("详细信息")
    button.config(state="disabled")
    # 创建 Text 控件,用于多行文本输入
    text_input = tk.Text(new_window, height=50, width=100)
    text_input.pack(padx=10, pady=10)
    try:
        for i in pdf_list:
            text_input.insert(tk.END, i + "\n")
        for i in word_list:
            text_input.insert(tk.END, i + "\n")
        for i in error_list:
            text_input.insert(tk.END, i + "\n")
    except:
        pass
        # 在 Text 控件中显示信息
        # text_input.insert(tk.END, "nihao" + "/n" + "shijie")

# 按钮,点击时打开新窗口
button = tk.Button(root, text="显示统计详细信息", command=open_new_window)
button.config(state="disabled")
button.pack(pady=20)

# 启动主循环
root.mainloop()



我用夸克网盘分享了「统计文件夹中pdf和word文件的页数.exe」,点击链接即可保存。打开「夸克APP」,无需下载在线播放视频,畅享原画5倍速,支持电视投屏。
链接:https://pan.quark.cn/s/aa377423113e

免费评分

参与人数 2吾爱币 +6 热心值 +2 收起 理由
wushaominkk + 5 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
luozi1653 + 1 + 1 热心回复!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

anxingye 发表于 2024-4-2 19:55
很有借鉴意义,已学习。
gs129090 发表于 2024-4-2 20:00
52yu 发表于 2024-4-2 20:44
wan456 发表于 2024-4-2 21:18
直接查看后台打印进程不就可以吗?
arg10 发表于 2024-4-3 08:54
看着挺不错的
abcttud 发表于 2024-4-3 09:27
有其他盘吗
ignativs 发表于 2024-4-3 09:29
这个统计的是面还是页?如果双面打印有空白页怎么处理?
wulihubery31 发表于 2024-4-3 09:49
要是能有演示界面就更好了
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-3 03:00

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表