img_to_pdf.py 866 B

12345678910111213141516171819202122232425
  1. import argparse
  2. from PIL import Image
  3. import os
  4. from PyPDF2 import PdfFileReader, PdfFileWriter
  5. def img_to_pdf(img_path, save_path):
  6. img_list = os.listdir(img_path)
  7. out_pdf = PdfFileWriter()
  8. sdfs = [os.path.join(img_path, i) for i in img_list]
  9. for f in sdfs:
  10. img = Image.open(f)
  11. fw = f.replace('.jpg', '.pdf')
  12. img.save(fw)
  13. out_pdf.appendPagesFromReader(PdfFileReader(
  14. open(fw, 'rb'))) # 也可拆这句为 sc_pdf=PdfFileReader(open(fw,'rb')); out_pdf.addPage(sc_pdf.getPage(0))
  15. out_pdf.write(open(save_path, 'wb'))
  16. if __name__ == "__main__":
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument('--img_path', type=str, default='./images')
  19. parser.add_argument('--save_path', type=str, default='./pdf_file')
  20. args = parser.parse_args()
  21. img_to_pdf(args.img_path, args.save_path)