2020年9月16日 星期三

PYTHON提供旋轉rorate PDF

下面為PYTHON自訂旋轉PDF (將下列紅色部分,貼在Notepad記事本,另存成RoratePDF.py)

 # importing the required modules彙入相關必要之模組 

import PyPDF2 

import sys

#'開啟檔案總管 (開啟轉換後之檔案使用)'

import subprocess

#'開啟GUI 取得來源檔(找出欲旋轉之PDF檔案)

import tkinter as tk

from tkinter import filedialog


root = tk.Tk()

root.withdraw()


FilePathName = filedialog.askopenfilename(initialdir = "/",title = "Select file for rotate (選擇欲旋轉之PDF檔案)",filetypes = (("PDF files","*.pdf"),("all files","*.*")))


  

def PDFrotate(origFileName, newFileName, rotation): 

  

    # creating a pdf File object of original pdf 

    pdfFileObj = open(origFileName, 'rb') 

      

    # creating a pdf Reader object 

    pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 

  

    # creating a pdf writer object for new pdf 

    pdfWriter = PyPDF2.PdfFileWriter() 

      

    # rotating each page 

    for page in range(pdfReader.numPages): 

  

        # creating rotated page object 

        pageObj = pdfReader.getPage(page) 

        pageObj.rotateClockwise(rotation) 

  

        # adding rotated page object to pdf writer 

        pdfWriter.addPage(pageObj) 

  

    # new pdf file object 

    newFile = open(newFileName, 'wb') 

      

    # writing rotated pages to new file 

    pdfWriter.write(newFile) 

  

    # closing the original pdf file object 

    pdfFileObj.close() 

      

    # closing the new pdf file object 

    newFile.close() 

      

  

def main(): 

  

    # original pdf file name 

    origFileName = FilePathName

     

    # new pdf file name 

    newFileName = 'rotated_example.pdf'

      

    # rotation angle 自訂旋轉角度

    rotation_data = int(input("Enter a rotation angle(90、180): "))

      

    # calling the PDFrotate function 

    PDFrotate(origFileName, newFileName, rotation_data) 

      

if __name__ == "__main__": 

    # calling the main function 

    main()