本帖最后由 Endurance 于 2023-9-19 20:41 编辑
近日扫描了几页纸,需要合并成一个PDF文件,无奈网上的工具都要钱,所以研究了一下怎么使用python完成,发现不难,于是自己动手!
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 <input file name> <output file name>
来完成将图片附加在< output file name >的功能了。比如当前文件夹里有page-1.jpg到page-100.jpg一共100个图片,就可以在命令提示符里使用
for /l %i in (1,1,100) do python merge_images.py page-%i.jpg output.pdf
进行合并。
|