Skip to content

Instantly share code, notes, and snippets.

@khlizard
Last active July 10, 2024 00:57
Show Gist options
  • Save khlizard/a2b3b0d92ad15f762ade6445e3c8f067 to your computer and use it in GitHub Desktop.
Save khlizard/a2b3b0d92ad15f762ade6445e3c8f067 to your computer and use it in GitHub Desktop.
Image to PDF. It is recommended to put it in SendTo.
@echo off
cd %~dp0
python img2pdf.py %*
echo.
@REM pause
echo It will automatically end after 3 seconds...
choice /C YN /D Y /T 3 /N > NUL
from fpdf import FPDF
from PIL import Image
import os
import sys
from datetime import datetime
import tempfile
def make_pdf(image_paths, output_pdf_name):
pdf = FPDF(unit="pt", format='A4')
page_width = 595
page_height = 842
temp_files = []
for image_path in image_paths:
img = Image.open(image_path)
original_format = img.format or 'PNG' # 元のフォーマットがNoneの場合はデフォルトで'PNG'を使用
# 画像が幅より高さが短い場合、左に90度回転
if img.width > img.height:
img = img.rotate(90, expand=True)
# 画像がパレットモードの場合、JPEGではなくPNGとして保存
if img.mode == 'P' and original_format == 'PNG':
img = img.convert('RGB') if original_format != 'PNG' else img
ratio = min(page_width / img.width, page_height / img.height)
new_width = int(img.width * ratio)
new_height = int(img.height * ratio)
x = (page_width - new_width) / 2
y = (page_height - new_height) / 2
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{original_format.lower()}") as tmpfile:
img.save(tmpfile.name, original_format) # 元のフォーマットを使用して保存
temp_files.append(tmpfile.name)
pdf.add_page()
pdf.image(tmpfile.name, x, y, new_width, new_height)
pdf.output(output_pdf_name)
print(f"PDFファイルを作成しました: {output_pdf_name}")
for file in temp_files:
os.unlink(file)
if __name__ == "__main__":
image_paths = sys.argv[1:]
if image_paths:
image_paths = sorted(image_paths)
output_folder = os.path.dirname(image_paths[0])
current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
output_pdf_name = os.path.join(output_folder, f'output_{current_time}.pdf')
make_pdf(image_paths, output_pdf_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment