Python/이것저것 파이썬
[python] image2pdf
컴닥
2024. 8. 3. 18:17
반응형
파이썬으로 이미지를 모아서 PDF를 만드는 코드 입니다.
pillow만 사용해도 가능합니다.
pip install pillow
import os
from PIL import Image
path = '/Volumes/a/b/c'
files = os.listdir(path)
files.sort()
print(*files[:5], '...', *files[-5:])
images = []
for index, file in enumerate(files):
if file.endswith('.jpg') or file.endswith('.png'):
print('\r', index, file, end='')
image = Image.open(os.path.join(path, file)).convert('RGB')
images.append(image)
images[0].save('new.pdf', save_all=True, append_images=images[1:])
print('\r완료')
프린트 문에서 같은 행에 반복해서 번호와 파일명을 출력하는 트릭을 사용했습니다.
자잘한 트릭이 몇 가지 들어간 코드니 재미있게 봐 주시길...
리스트 컴프리헨션을 이용해 줄인다면...
하지만 리스트 컴프리헨션 내에서는 프린트 문을 쓸 수가 없어서....
import os
from PIL import Image
path = '/Volumes/a/b/c'
files = os.listdir(path)
files.sort()
print(*files[:5], '...', *files[-5:])
images = [Image.open(os.path.join(path, file)).convert('RGB') for file in files if file.endswith('.jpg') or file.endswith('.png')]
images[0].save('new.pdf', save_all=True, append_images=images[1:])
print('\r완료')
반응형