#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import sys
import time
import fitz
import PyPDF2
import win32api
import win32print
import easygui as EG
from pdfminer.pdfparser import  PDFParser,PDFDocument
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed, PDFResourceManager, PDFPageInterpreter

Brooks = 'Commercial Excellence Team - OA'
PrinterPath = r'\\SUZ-PRINTER\SUZ_B1_8F_Sales'

def Printer(PrinterDir):
    currentprinter = win32print.GetDefaultPrinter()
    FileNames = os.listdir(PrinterDir)
    for FileName in FileNames:
        if FileName.endswith("pdf"):
            FilePath = os.path.join(PrinterDir,FileName)
            if (currentprinter==PrinterPath):
                win32api.ShellExecute(0, "print", FilePath, None,  ".",  0)
            else:
                win32print.SetDefaultPrinter(PrinterPath)
                win32api.ShellExecute(0, "print", FilePath, None,  ".",  0)
    os.system("explorer.exe %s" % PrinterDir)
    sys.exit()

def PdfFileMerger(DirPath):
    DirName = os.path.basename(DirPath)
    PDF = os.getcwd() + '\\' + DirName + '.pdf'
    if not os.path.exists(PDF):
        pdf_list = [f for f in os.listdir(DirPath) if f.endswith('.pdf')]
        pdf_list = [os.path.join(DirPath, filename) for filename in pdf_list]
        File_merger = PyPDF2.PdfFileMerger()
        for pdf in pdf_list:
            File_merger.append(pdf)
        File_merger.write(PDF)
        os.system("explorer.exe %s" % PDF)
        sys.exit()
    else:
        EG.msgbox(msg=PDF, title=Brooks, ok_button='合并文件已存在')
        os.system("explorer.exe %s" % PDF)
        sys.exit()

def PdfFileSplit(DirPath):
    zoom_x = 2.0
    zoom_y = 2.0
    PDF_FileNames = os.listdir(DirPath)
    for PDF_FileName in PDF_FileNames:
        if PDF_FileName.endswith('pdf'):
            PDF_FilePath = os.path.join(DirPath,PDF_FileName)
            doc = fitz.open(PDF_FilePath)
            for pg in range(doc.page_count):
                page = doc[pg]
                trans = fitz.Matrix(zoom_x,zoom_y)
                pm = page.get_pixmap(matrix=trans,alpha=False)
                PDFname = PDF_FileName.split('.')[0]
                PNGname = PDFname + '_' + str(pg) + '.png'
                pm.save(DirPath + '\\' + PNGname)
            doc.close()
    os.system("explorer.exe %s" % DirPath)
    sys.exit()

def Pdf2txt(DirPath):
    PDF_FileNames = os.listdir(DirPath)
    for PDF_FileName in PDF_FileNames:
        if PDF_FileName.endswith('pdf'):
            PDF_FilePath = os.path.join(DirPath,PDF_FileName)
            TXTname = PDF_FileName.split('.')[0] + '.txt'
            TXT_FilePath = os.path.join(DirPath,TXTname)
            fp = open(PDF_FilePath,'rb')
            parser = PDFParser(fp)
            doc = PDFDocument()
            parser.set_document(doc)
            doc.set_parser(parser)
            doc.initialize()
            if not doc.is_extractable:
                raise PDFTextExtractionNotAllowed
            else:
                rsrcmgr = PDFResourceManager()
                laparams = LAParams()
                device = PDFPageAggregator(rsrcmgr,laparams=laparams)
                interpreter = PDFPageInterpreter(rsrcmgr,device)
                for page in doc.get_pages():
                    interpreter.process_page(page)
                    layout = device.get_result()
                    for x in layout:
                        if(isinstance(x,LTTextBoxHorizontal)):
                            with open(TXT_FilePath,'a') as f:
                                results = x.get_text()
                                f.write(results  +"\n")
    os.system("explorer.exe %s" % DirPath)
    sys.exit()

if __name__ == '__main__':
    GO = EG.buttonbox(title=Brooks, choices=("批量PDF打印","批量PDF合并","批量PDF分割","批量PDF提取"))
    if GO == '批量PDF打印':
        DirPath = EG.diropenbox(title=Brooks)
        if (DirPath != None):
            Printer(DirPath)
        else:
            sys.exit()
    elif GO == '批量PDF合并':
        DirPath = EG.diropenbox(title=Brooks)
        if (DirPath != None):
            PdfFileMerger(DirPath)
        else:
            sys.exit()
    elif GO == '批量PDF分割':
        DirPath = EG.diropenbox(title=Brooks)
        if (DirPath != None):
            PdfFileSplit(DirPath)
        else:
            sys.exit()
    elif GO == '批量PDF提取':
        DirPath = EG.diropenbox(title=Brooks)
        if (DirPath != None):
            Pdf2txt(DirPath)
        else:
            sys.exit()
    else:
        while True:
            xzhou = EG.msgbox(msg='灵魂拷问:谁是世界上最帅的人???', title=Brooks, ok_button='周晓竞')
            if xzhou:
                sys.exit()
            else:
                continue
    
COURIER ● 豫ICP备2020027789号 ● XZHOU