Cómo convertir por lotes archivos JPG a PDF usando VBA o Python
# -*- codificación:utf-8 -*-
#!/usr/bin/env python
importar sistema operativo
desde reportlab.lib.pagesizes importar A4, horizontal
desde reportlab.pdfgen importar lienzo
desde tkinter importar *
importar tiempo
# Lista de nombres de archivos de imagen
IMAGEFILES = []
class pdfTk(object):
def __init__(self):
'''Se utiliza para generar la interfaz principal para completar'''
self.top = Tk()
self.sw = self.top.winfo_screenwidth()
self.sh = self.top.winfo_screenheight()
self.topw = 500
self.toph = 200
self.top. title ('Generador de imagen a 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 , altura=50)
self.emptfmone.pack()
self.dirfm = Marco(self.top)
self.descriptLabel = Etiqueta(self .dirfm, ancho=4, texto='Ruta:')
self.descriptLabel.pack(lado=IZQUIERDA)
self.dirn = Entrada(self.dirfm, ancho= 50, textvariable=self._DIRPATH)
#self.dirn.bind('
self.dirn.pack(side=IZQUIERDA)
self.dirfm.pack()
self.emptfmtwo = Marco(self.top, altura=30)
self.emptfmtwo.pack() p>
self.btnfm = Marco(self.top)
self.converBtn = Botón(self.btnfm, ancho=10, texto='Generar PDF', comando=self.doneAnyThing,
activeforeground='blanco', activebackground='azul')
self.quitBtn = Botón(self.btnfm, ancho=10, texto='Salir', comando=self.top .salir, activeforeground='blanco',
a
ctivefondo='azul')
self.converBtn.pack(lado=IZQUIERDA, padx=10)
self.quitBtn.pack(lado=IZQUIERDA, padx=10) p> p>
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):
'''Varias imágenes en un archivo pdf'''
(ancho, alto) = paisaje(A4) #
cv = canvas.Canvas(pdfFile, pagesize=landscape(A4))
para imagePath en IMAGEFILES:
cv.drawImage(imagePath, 0, 0, w, h) p >
cv.showPage()
cv.save()
def getListImages(self, dirPath):
''Lea lo especificado file Recorte todas las imágenes JPEG y guárdelas en la lista'''
si dirPath es Ninguno o len(dirPath) == 0:
raise ValueError('dirPath no puede estar vacío, El valor es la carpeta de ruta específica donde se almacena la imagen ')
if os.path.isfile(dirPath):
raise ValueError('dirPath no puede ser un archivo específico). , el valor es el almacenamiento La carpeta de ruta específica de la imagen ')
if os.path.isdir(dirPath):
para imageName en os.listdir(dirPath):
if nombreImagen.endswith('.jpg') o nombreImagen.endswith('.jpeg'):
absPath = self.converPath(dirPath) + nombreImagen
IMAGEFILES.append(absPath )
def converPath(self, dirPath):
''' se usa para convertir la ruta, determine si la ruta es \\, si es así , envíelo directamente, si no, agregue ' ''
si dirPath es Ninguno o len(dirPath) == 0:
raise ValueError('dirPath no puede estar vacío. ')
if os.path.isfile(dirPath):
raise ValueError('dirPath no puede ser un archivo específico, ¡el valor es una ruta de carpeta!')
si no str(dirPath).endswith("\\"):
devuelve dirPath + "\\"
devuelve dirPath
def dateStr ( self):
''' se utiliza para generar una fecha en un formato específico con el fin de empalmar cadenas'''
>return time.strftime("%Y-%m-%d", time.localtime())
def main():
'''Esta función se utiliza principalmente Generar archivo PDF '''
pdfTk()
mainloop()
if __name__ == '__main__':
'' 'Función principal, inicio''''
main()