利用python将夏普WG-S20输出的BMP转化成pdf并合并

来源:互联网 发布:程序员平均工资 编辑:程序博客网 时间:2024/05/17 09:16

使用方式:
1. 命令行下 或者(cmd)进入image2pdf.py 所在文件夹 image2pdf.py下载
2. 输入 python image2pdf.py EXPORT EXPORT1 EXPORT2
3. EXPORT 为导出的电子笔记图片,格式为bmp (直接将电子笔记输出的文件夹EXPORT复制过来就行了
4. 输出pdf在EXPORT2 这个同级文件夹里 名字为full_pdf 记得改名就行

代码如下:

# !/usr/bin/python# -*- coding: utf-8 -*- from PIL import Imagefrom PyPDF2 import PdfFileWriter, PdfFileReaderimport osfrom tqdm import tqdmimport sys##图片转化成pdf函数def image2pdf(image_dir,output_dir,image_type='bmp'):    #判断是否存在输出目录,没有则创建        if not os.path.exists(output_dir):            os.mkdir(output_dir)      #判断图片文件夹是否存在        if not os.path.exists(image_dir):            raise Exception(u'图片目录不存在,请重新输入')    #读取输入文件夹名字并读取        all_images=os.listdir(image_dir)        for each in tqdm(all_images):            image_name=os.path.join(image_dir,each)            if os.path.isfile(image_name):                if each.endswith(image_type):                    im=Image.open(image_name)                    im2pdf=os.path.splitext(each)[0].lstrip('Page00')+'.pdf'                    pdf_name=os.path.join(output_dir,im2pdf)                    im.save(pdf_name)         print u'图片转成pdf成功,pdf生成文件夹在%s'% output_dir##将单个pdf合成一个pdf函数                            def merge_pdf(pdf_dir,pdf_names='full_pdf',output_dir=''):    #将文件夹内单个pdf合并成一个大的pdf    #判断图片文件夹是否存在        if not os.path.exists(pdf_dir):            raise Exception(u'输入目录不存在,请重新输入')        if output_dir =='':            output_dir=pdf_dir    #判断是否存在输出目录,没有则创建        if not os.path.exists(output_dir):            os.mkdir(output_dir)      ##开始合并        all_pdfs=os.listdir(pdf_dir)        n_pdfs=len(all_pdfs)-1        pdf_output = PdfFileWriter()        for num in tqdm(range(n_pdfs)):            pdf_name=str(num+1)+'.pdf'            if pdf_name in all_pdfs:                try:                    full_name=os.path.join(pdf_dir,pdf_name)                    input_one = file(full_name, 'rb')                    pdf_input = PdfFileReader(input_one)                    page=pdf_input.getPage(0)                    pdf_output.addPage(page)                except Exception as e:                    print e                    continue        if not pdf_names.endswith('.pdf'):            pdf_names=pdf_names+'.pdf'        full_path=os.path.join(output_dir,pdf_names)        output_stream = file( full_path,'wb')        pdf_output.write(output_stream)         output_stream.close()        print u'合并完成'##输入图片文件夹 pdf存放文件夹 完整pdf输出的文件夹  image_dir=os.path.join(os.getcwd(),sys.argv[1])output_dirs=os.path.join(os.getcwd(),sys.argv[2])image2pdf(image_dir,output_dirs,image_type='bmp')output_dir=os.path.join(os.getcwd(),sys.argv[3])merge_pdf(output_dirs,pdf_names='full_pdf',output_dir=output_dir)
0 0
原创粉丝点击