目录
法一
法二
法一
完整版,能解决诸如图片旋转问题、图片保存为A4格式问题等,只需把图片放到一个文件夹里,然后在文件夹外放上下面的代码,即可。
from reportlab.pdfgen import canvasfrom reportlab.lib.units import inch, cmfrom reportlab.lib.pagesizes import letterfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Image, PageBreakfrom reportlab.lib.pagesizes import A4,A3,A2,A1, legal, landscapefrom reportlab.lib.utils import ImageReaderimport PIL.Image,PIL.ExifTagsfrom os import listdirimport os,reimport timefrom reportlab.lib.units import inchdef img_search(mypath, filenames):for lists in os.listdir(mypath):path = os.path.join(mypath,lists)if os.path.isfile(path):expression = r'[\w]+\.(jpg|png|jpeg)$'if re.search(expression, path, re.IGNORECASE):filenames.append(path)elif os.path.isdir(path):img_search(path, filenames)def img_search1(mypath, filenames):for lists in os.listdir(mypath):path = os.path.join(mypath,lists)if os.path.isfile(path):a = path.split('.')if a[-1] in ['jpg', 'png', 'JPEG']:filenames.append(path)elif os.path.isdir(path):img_search1(path,filenames)def rotate_img_to_proper(image):try:# image = Image.open(filename)if hasattr(image, '_getexif'): # only present in JPEGsfor orientation in PIL.ExifTags.TAGS.keys():if PIL.ExifTags.TAGS[orientation] == 'Orientation':breake = image._getexif() # returns None if no EXIF dataif e is not None:#log.info('EXIF data found: %r', e)exif = dict(e.items())orientation = exif[orientation]# print('found, ',orientation)if orientation == 3:image = image.transpose(Image.ROTATE_180)elif orientation == 6:image = image.transpose(Image.ROTATE_270)elif orientation == 8:image = image.rotate(90,expand=True)except:passreturn imagedef main(src_folder=None):output_file_name = 'out.pdf'#save_file_name = 'ex.pdf'#doc = SimpleDocTemplate(save_file_name, pagesize=A1,# rightMargin=72, leftMargin=72,# topMargin=72, bottomMargin=18)imgDoc = canvas.Canvas(output_file_name)#pagesize=letterimgDoc.setPageSize(A4)document_width,document_height = A4if src_folder is None: mypath = input('Input the image folder please:')else: mypath = src_folderfilenames=[]start = time.clock()img_search(mypath, filenames)end = time.clock()print('find file cost time: ', end-start, 'find files: ', len(filenames))# for f in filenames:#print(f)for image in filenames:try:image_file = PIL.Image.open(image)image_file = rotate_img_to_proper(image_file)image_width, image_height = image_file.sizeprint('img size:', image_file.size)if not(image_width>0 and image_height>0):raise Exceptionimage_aspect = image_height/float(image_width)#Determins the demensions of the image in the overviewprint_width = document_widthprint_height = document_width*image_aspectimgDoc.drawImage(ImageReader(image_file),document_width-print_width,document_height-print_height,width=print_width,height=print_height,preserveAspectRatio=True)#inform the reportlab we want a new pageimgDoc.showPage()except Exception as e:print('error:',e,image)imgDoc.save()print('Done')if __name__ == '__main__':main(src_folder=None);
法二
入门版,解决多个图片合并为PDF问题,具体代码可参见此博文。
But,我自己没有成功运行出来,so参考这篇问答中的第一个answer,得到以下仅能将单图转为PDF的代码(如有博友解决,还望不吝赐教)。
from PIL import Imageimport osdef rea():file_list = os.listdir('.')pic_name = []im_list = []for x in file_list:if "jpg" in x or 'png' in x or 'jpeg' in x:pic_name.append(x)pic_name.sort()new_pic = []for x in pic_name:if "jpg" in x:new_pic.append(x)for x in pic_name:if "png" in x:new_pic.append(x)print("hec", new_pic)png = Image.open(new_pic[0]).convert('RGBA')png.load()background = Image.new('RGB', png.size, (255,255,255))background.paste(png, mask=png.split()[3]) background.save('xxx.pdf', 'PDF', quality=80)if __name__ == '__main__':tttt = """_____ _____ _____ _______ ____ _____ _____ ______ | __ \_ _/ ____| |__ __/ __ \ | __ \| __ \| ____|| |__) || || || | | | | | | |__) | | | | |__ | ___/ | || || | | | | | | ___/| | | | __| | | _| || |____ | | | |__| | | | | |__| | | |_| |_____\_____| |_| \____/ |_| |_____/|_| """print(tttt)print("合成")rea()