2021-09-23

HBH 定制jpg转pdf

import glob
import fitz  # 导入本模块需安装pymupdf库
import os



# 将文件夹中指定jpg图片转换为指定名称的pdf文件,并保存至指定文件夹
def pic2pdf_2(img_path, pdf_path, img_list, pdf_name):
    doc = fitz.open()
    pic_list = [img_path+i for i in img_list]

    for img in sorted(pic_list):
        imgdoc = fitz.open(img)
        pdfbytes = imgdoc.convertToPDF()
        imgpdf = fitz.open("pdf", pdfbytes)
        doc.insertPDF(imgpdf)

    doc.setToC(gen_pdf_MBY(img_list))
    doc.save(pdf_path + pdf_name)
    doc.close()


# 生成目录 标题 页码
def gen_pdf_MBY(list):
    abstract_list = []

    counter = 1
    for i in list:
        if not isinstance(i,str):
            return "非字符串"
        i = i.split(".")[0]
        abstract_list.append([1,i,counter])
        counter+=1

    return abstract_list




# 获取所有文件夹
def get_folder(path):
    path_list = [path+i for i in os.listdir(path)]
    folderName_list = os.listdir(path)


    folder_list = []
    for path in path_list:
        if os.path.isdir(path):
            folder_list.append(path)
        else:
            folderName_list.pop()

    return folder_list,folderName_list




if __name__ == '__main__':
    img_path = r'E:/codeDemo/imgs/'
    pdf_path = r'E:/codeDemo/pdfs/'

    path_list,file_name = get_folder(img_path)
    print(path_list,file_name)
    for img,pdf in zip(path_list,file_name):
        img_list = os.listdir(img)
        pdf_name = pdf+".pdf"
        print(img_list,pdf_name)
        # img_list, pdf_name1 = [r'tu_1.jpg', r'tu_2.jpg'], r'2.pdf'
        pic2pdf_2(img_path=img+"/", pdf_path=pdf_path, img_list=img_list, pdf_name=pdf_name)
上一篇:在递归中使用迭代器


下一篇:EasyUI入门