import os
import time
import re
from IPython.display import clear_output
from PIL import Image
from google.colab import drive
drive.mount('/content/drive', force_remount=False)
try:
from fpdf import FPDF
except:
!git clone https://github.com/reingart/pyfpdf.git
%cd pyfpdf
!python setup.py install
from fpdf import FPDF
clear_output()
class Img_to_Pdf:
def chapter_to_pdf(self, path, ):
os.chdir(path)
imagelist = os.listdir(path)
imagelist.sort(key=lambda x: int(re.search("^(\d+)",x).group(1)))
pdf = FPDF()
pdf.set_display_mode("default", layout="continuous")
for image in imagelist:
photo = Image.open(image)
width = photo.size[0]
height = photo.size[1]
pdf.add_page(orientation='P', format=(width, height))
self.pdf_add_image(pdf, image, width, height, ext=('jpeg', 'jpg', 'png', 'gif', ))
pdf.output(os.path.join(path, "output.pdf"), "F")
def pdf_add_image(self, pdf, image, width, height, **kwargs):
Error = []
for ext in kwargs['ext']:
try:
pdf.image(image, x=0, y=0, w=width, h=height, type=ext)
return True
except Exception as e:
Error.append(f'Image_Name: {image},\n{str(e)}')
raise TypeError("\n\n".join(Error))
def execute_command(self, path, **kwargs):
self.chapter_to_pdf(path)
if kwargs['delete_image']:
print("轉換成功...正在刪除相關圖片,請稍後。")
for file in os.listdir(path):
if (file.endswith('.jpg') or file.endswith('.png') or file.endswith('.gif') or file.endswith('.jpeg')):
os.remove(file)
print("刪除圖片完成。")
else:
print("轉換成功")
path = f"/content/drive/MyDrive/{your_image_folder}/"
Img_to_Pdf().execute_command(path, delete_image = True)