python,多圖片轉換成pdf文件


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

import os
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
from tkinter import *
import time

# 圖片文件名稱列表
IMAGEFILES = []
class pdfTk(object):

def __init__(self):
'''用於生成主界面用於填寫'''
self.top = Tk()
self.sw = self.top.winfo_screenwidth()
self.sh = self.top.winfo_screenheight()
self.topw = 500
self.toph = 200
self.top.title('圖片轉pdf生成器')
self.top.geometry("%dx%d+%d+%d" % (self.topw, self.toph, (self.sw - self.topw) / 2, (self.sh - self.toph) / 2))

self._DIRPATH = StringVar(self.top)

self.emptfmone = Frame(self.top, height=50)
self.emptfmone.pack()

self.dirfm = Frame(self.top)
self.descriptLabel = Label(self.dirfm, width=4, text='路徑:')
self.descriptLabel.pack(side=LEFT)
self.dirn = Entry(self.dirfm, width=50, textvariable=self._DIRPATH)
#self.dirn.bind('<Return>', self.setPath)
self.dirn.pack(side=LEFT)
self.dirfm.pack()

self.emptfmtwo = Frame(self.top, height=30)
self.emptfmtwo.pack()

self.btnfm = Frame(self.top)
self.converBtn = Button(self.btnfm, width=10, text='生成PDF', command=self.doneAnyThing,
activeforeground='white', activebackground='blue')
self.quitBtn = Button(self.btnfm, width=10, text='退出', command=self.top.quit, activeforeground='white',
activebackground='blue')
self.converBtn.pack(side=LEFT, padx=10)
self.quitBtn.pack(side=LEFT, padx=10)
self.btnfm.pack()

def doneAnyThing(self):
self.getListImages(self._DIRPATH.get())
pdfFile = self.converPath(self._DIRPATH.get()) + self.dateStr() + ".pdf"
self.convertpdf(pdfFile)

def convertpdf(self, pdfFile):
'''多個圖片合成一個pdf文件'''
(w, h) = landscape(A4) #
cv = canvas.Canvas(pdfFile, pagesize=landscape(A4))
for imagePath in IMAGEFILES:
cv.drawImage(imagePath, 0, 0, w, h)
cv.showPage()
cv.save()

def getListImages(self, dirPath):
'''讀取指定文件夾下所有的JPEG圖片,存入列表'''
if dirPath is None or len(dirPath) == 0:
raise ValueError('dirPath不能為空,該值為存放圖片的具體路徑文件夾!')
if os.path.isfile(dirPath):
raise ValueError('dirPath不能為具體文件,該值為存放圖片的具體路徑文件夾!')
if os.path.isdir(dirPath):
for imageName in os.listdir(dirPath):
if imageName.endswith('.jpg') or imageName.endswith('.jpeg'):
absPath = self.converPath(dirPath) + imageName
IMAGEFILES.append(absPath)

def converPath(self, dirPath):
'''用於轉換路徑,判斷路徑后是否為\\,如果有則直接輸出,如果沒有則添加'''
if dirPath is None or len(dirPath) == 0:
raise ValueError('dirPath不能為空!')
if os.path.isfile(dirPath):
raise ValueError('dirPath不能為具體文件,該值為文件夾路徑!')
if not str(dirPath).endswith("\\"):
return dirPath + "\\"
return dirPath

def dateStr(self):
'''用於生成指定格式的日期,目的是為了拼接字符串'''
return time.strftime("%Y-%m-%d", time.localtime())

def main():
'''該函數主要用於生成PDF文件'''
pdfTk()
mainloop()

if __name__ == '__main__':
'''主函數,進行啟動'''
main()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM