25
2022
03

Multi-images to pdf

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(selfpath, ):
    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(selfpdfimagewidthheight, **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(selfpath, **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


« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。