import os
from PIL import Image
import sys
from PyPDF2 import PdfWriter,PdfReader
def merge_images_to_pdf(input_filename, output_filename):
pdf_writer = PdfWriter()
#pdf_reader = PdfReader()
image_path = os.path.join('./', input_filename)
img = Image.open(image_path)
temp_pdf_filename = f'{input_filename}.pdf'
img.save(temp_pdf_filename, format='PDF')
if os.path.exists(output_filename):
with open(output_filename, 'rb') as temp_pdf0:
pdf_reader = PdfReader(temp_pdf0)
for pages in pdf_reader.pages:
pdf_writer.add_page(pages)
with open(temp_pdf_filename, 'rb') as temp_pdf:
pdf_reader = PdfReader(temp_pdf)
for page in pdf_reader.pages:
pdf_writer.add_page(page)
with open(output_filename, 'wb') as output:
pdf_writer.write(output)
input_filename = sys.argv[1]
output_filename = sys.argv[2]
merge_images_to_pdf(input_filename, output_filename)
保存成merge_images.py;
之后,就可以使用命令
python merge_images.py [i]
来完成将图片附加在的功能了。比如当前文件夹里有page-1.jpg到page-100.jpg一共100个图片,就可以在命令提示符里使用
for /l %i in (1,1,100) do python merge_images.py page-%i.jpg output.pdf
进行合并。