jpg图片打包生成pdf文件的几种方式
img2pdf模块(固定成A4纸张大小):
import img2pdf def makePdf(pdfFileName, jpg_name_list): a4inpt = (img2pdf.mm_to_pt(210),img2pdf.mm_to_pt(297)) layout_fun = img2pdf.get_layout_fun(a4inpt) with open(pdfFileName,'wb') as f: f.write(img2pdf.convert(jpg_name_list, layout_fun=layout_fun))
PyPDF4模块(自己确定纸张大小):
def makePdf(pdfFileName, jpg_name_list): pdf_lis = [] for jpg_file in jpg_name_list: cover = Image.open(jpg_file) width, height = cover.size pdf = FPDF(unit="pt", format=[width, height]) pdf.add_page() pdf.image(jpg_file, 0, 0) pdf_lis.append(jpg_file + ".pdf") pdf.output(jpg_file + ".pdf", "F") merger = PyPDF4.PdfFileMerger() for filename in pdf_lis: merger.append(PyPDF4.PdfFileReader(filename)) merger.write(pdfFileName) for pdf_filename in pdf_lis: os.remove(pdf_filename)
以上两种可以保证转换的jpg图片保持在固定大小的纸张内,而不出现只有一半的错误