카테고리 없음

Directory to PDF Python 코드

truly-sparkle2 2023. 3. 18. 22:38

 

pip install pyqt5 Pillow reportlab

 

import datetime
import os
import sys

from PIL import Image
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog
from PyQt5.QtWidgets import QLabel, QDesktopWidget
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setAcceptDrops(True)
        self.initUI()

    def initUI(self):
        self.resize(300, 200)
        screen_center = QDesktopWidget().availableGeometry().center()
        widget_center = self.frameGeometry().center()
        self.move(screen_center - widget_center)

        self.setWindowTitle('PNG to PDF Converter')
        label = QLabel('Drag the folder', self)
        label.setAlignment(Qt.AlignCenter)
        label.move(self.rect().center() - label.rect().center())

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        urls = event.mimeData().urls()
        if len(urls) == 1 and urls[0].isLocalFile():
            path = str(urls[0].toLocalFile())
            if os.path.isdir(path) and any(f.endswith('.png') for f in
                                           os.listdir(path)):
                print("Path: ", path)
                print("Start Time: ", datetime.datetime.now())
                self.convert_directory(path)
                print("End Time: ", datetime.datetime.now())

    def convert_directory(self, png_dir):

        png_files = [os.path.join(png_dir, f) for f in os.listdir(png_dir) if f.endswith('.png')]
        sorted(png_files)

        pdf_file, _ = QFileDialog.getSaveFileName(self, "Save PDF2", png_dir.replace(' ', '') + ".pdf",
                                                  "PDF Files (*.pdf)")
        if not pdf_file:
            return
        pdf_canvas = canvas.Canvas(pdf_file, pagesize=letter)

        for png_file in png_files:
            img = Image.open(png_file)
            pdf_canvas.setPageSize((img.width, img.height))
            pdf_canvas.drawImage(png_file, 0, 0)
            pdf_canvas.showPage()

        pdf_canvas.save()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

 

 

반응형