From 7d6dc4e083d50acb0ae8fc805ebaf0442d01e394 Mon Sep 17 00:00:00 2001 From: NTGNguyen <23521049@gm.uit.edu.vn> Date: Tue, 20 Feb 2024 00:17:39 +0700 Subject: [PATCH] =?UTF-8?q?=E2=9C=85=20Add=20merge=5Fjpg=5Fto=5Fpdf=20meth?= =?UTF-8?q?od=20to=20CreatePDF=20class?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/modules/create_pdf.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/modules/create_pdf.py b/src/modules/create_pdf.py index fd18ea4..a2dedb1 100644 --- a/src/modules/create_pdf.py +++ b/src/modules/create_pdf.py @@ -1,6 +1,7 @@ """Merge the images of books into PDF files""" - +import os +import img2pdf from .link_parse import LinkFile, Link @@ -13,3 +14,25 @@ class CreatePDF: def __init__(self, links: list[Link]) -> None: self.links = links + + @staticmethod + def merge_jpg_to_pdf(directory, book_name) -> None: + """Merge all JPG images in a directory into a single PDF. + + Args: + directory (str): The directory containing the JPG images. + output_filename (str): The filename of the output PDF. + + Returns: + None + """ + jpg_files = [f for f in os.listdir(directory) if f.endswith('.jpg')] + jpg_files.sort() + jpg_files = [os.path.join(directory, f) for f in jpg_files] + if jpg_files: + pdf_bytes = img2pdf.convert(jpg_files) + if pdf_bytes is not None: + with open(book_name, 'wb') as f: + f.write(pdf_bytes) + else: + print("No JPG images found in the directory.")