def main(): prs = Presentation('template_red.pptx') title_slidelayout = prs.slidemasters[0].slidelayouts[0] slide = prs.slides.add_slide(title_slidelayout) title = slide.shapes.title subtitle = slide.shapes.placeholders[1] title.text = "Title!" subtitle.text = "subtitle" #-------glob current folder Dirs = ['./fig/'] psJpgs = searchAllPsJpgs(Dirs) for psJpg in psJpgs: psJpg.printAll() allSlides = sortGrpPsJpgs(psJpgs) # slidesEachNumField(prs, allSlides) slidesCompareFields(prs, allSlides) slidesCompareNum(prs, allSlides) #------------------------------------------ Dirs = [o for o in glob.glob('../../Run/*') if os.path.isdir(o)] for Dir in Dirs: Dir = Dir.replace("\\", "/") print "Dirs=", Dirs psJpgs = searchAllPsJpgs(Dirs) allSlides = sortGrpPsJpgs(psJpgs) slidesEachNumField(prs, allSlides) slidesCompareFields(prs, allSlides) slidesCompareNum(prs, allSlides) foutName = 'printout_cfdresults.pptx' prs.save(foutName)
class PptManager(object): """docstring for PptManager""" def __init__(self): self.prs = Presentation() self.k_graph = K_Graph() self.k_graph.save() def addSlide(self,input): # Create layout bullet_slide_layout = self.prs.slide_layouts[1] slide = self.prs.slides.add_slide(bullet_slide_layout) # Create shape shapes = slide.shapes title_shape = shapes.title body_shape = shapes.placeholders[1] # Add slide elements title_shape.text = input tf = body_shape.text_frame # Create points processor = ProcessManager(input) # Process input processor.setSlideElements() elements = processor.getSlideElements() # elements are { (l1,c1), (l2,c2), ... } # Traverse through elements to add slide components ... # point = (level,content) for point in elements: p = tf.add_paragraph() p.font.size = Pt(20) p.level = point[0] p.text = point[1] def savePPT(self): self.prs.save('test.pptx')
def to_pptx(self): logger.info('Converting svg -> html -> png -> pptx') content = None try: # convert to png png_fn = self._rasterize_png() # create blank presentation slide layout pres = Presentation() blank_slidelayout = pres.slide_layouts[6] slide = pres.slides.add_slide(blank_slidelayout) self._pptx_add_title(slide) self._pptx_add_url(slide) self._pptx_add_png(slide, png_fn) self._pptx_add_hawc_logo(slide) # save as object content = BytesIO() pres.save(content) content.seek(0) except Exception as e: logger.error(e, exc_info=True) finally: self.cleanup() return content
def df_to_powerpoint(filename, df, **kwargs): """Converts a Pandas DataFrame to a table in a new, blank PowerPoint presentation. Creates a new PowerPoint presentation with the given filename, with a single slide containing a single table with the Pandas DataFrame data in it. The table is a standard Powerpoint table, and can easily be modified with the Powerpoint tools, for example: resizing columns, changing formatting etc. Parameters ---------- filename: Filename to save the PowerPoint presentation as df: pandas ``DataFrame`` DataFrame with the data **kwargs All other arguments that can be taken by ``df_to_table()`` (such as ``col_formatters`` or ``rounding``) can also be passed here. Returns ------- pptx.shapes.graphfrm.GraphicFrame The python-pptx table (GraphicFrame) object that was created (which can then be used to do further manipulation if desired) """ pres = Presentation() blank_slide_layout = pres.slide_layouts[6] slide = pres.slides.add_slide(blank_slide_layout) table = df_to_table(slide, df, **kwargs) pres.save(filename) return table
def analyze_ppt(input, output): """ Take the input file and analyze the structure. The output file contains marked up information to make it easier for generating future powerpoint templates. """ prs = Presentation(input) # Each powerpoint file has multiple layouts # Loop through them all and see where the various elements are for index, _ in enumerate(prs.slide_layouts): slide = prs.slides.add_slide(prs.slide_layouts[index]) # Not every slide has to have a title try: title = slide.shapes.title title.text = 'Title for Layout {}'.format(index) except AttributeError: print("No Title for Layout {}".format(index)) # Go through all the placeholders and identify them by index and type for shape in slide.placeholders: if shape.is_placeholder: phf = shape.placeholder_format # Do not overwrite the title which is just a special placeholder try: if 'Title' not in shape.text: shape.text = 'Placeholder index:{} type:{}'.format(phf.idx, shape.name) except AttributeError: print("{} has no text attribute".format(phf.type)) print('{} {}'.format(phf.idx, shape.name)) prs.save(output)
def main(trac_id, trac_pass, this_round): pptfile = '%s_tickets.pptx' % this_round print('\n' + pptfile) trac_rpc_url = 'http://%s:%s@%s/login/rpc' % (trac_id, trac_pass, trac_url) server = xmlrpc.client.ServerProxy(trac_rpc_url) tlist = server.ticket.query('owner=%s&due_date^=%s' % (name, this_round)) tickets = [] for t in tlist: ticket = server.ticket.get(t) print('ticket collected. #%d %s' % (t, ticket[3]['summary'])) tickets.append(ticket) prs = Presentation('ticket.pptx') cell_texts = [] t_idx = 0 for slide in prs.slides: for shape in slide.shapes: if not shape.has_table: continue for row in shape.table.rows: for cell in row.cells: process_set_text(cell, cell_texts, tlist[t_idx], tickets[t_idx], this_round) cell_texts.append(cell.text_frame.text) # 한 티켓의 입력이 끝날때, 다음 티켓 입력할지 종료할지 결정 if cell_texts[-1] == '실행자': if len(tlist) - 1 <= t_idx: prs.save(pptfile) return else: t_idx = t_idx + 1
def create_presentation(suras, sura_number, outputfile, start=None, end=None, arabic_font="Calibri"): prs = Presentation() title_slide_layout = prs.slide_layouts[0] slide = prs.slides.add_slide(title_slide_layout) title = slide.shapes.title subtitle = slide.placeholders[1] title.text = "Sura %s" % (SURA_NAMES[sura_number],) if start: subtitle.txt = "Ayat %s to %s" % (start, end) blank_slide_layout = prs.slide_layouts[6] if sura_number != 9 and not (sura_number == 1 and (start is None or int(start) == 1)): # add bismillah ayat = suras[1][1] slide = prs.slides.add_slide(title_slide_layout) title = slide.shapes.title title.text_frame.paragraphs[0].text subtitle = slide.placeholders[1] title.text = ayat["arabic"] title.text_frame.paragraphs[0].font.name = arabic_font subtitle.text = ayat["english"] for number, ayat in suras[sura_number].iteritems(): if start is None or (number >= int(start) and number <= int(end)): slide = prs.slides.add_slide(title_slide_layout) title = slide.shapes.title subtitle = slide.placeholders[1] title.text = ayat["arabic"] title.text_frame.paragraphs[0].font.name = arabic_font subtitle.text = ayat["english"] + " [{}]".format(number) prs.save(outputfile)
def image_folder2pptx(fd,ppname,nrow,ncol,picwidth,picheight,\ resize=False, reposition = True): if resize: step_x = SLIDE_WIDTH/ncol step_y = SLIDE_HEIGHT/nrow else: step_x = util.Px(picwidth) step_y = util.Px(picheight) #print("test") #print step_x, step_y, picwidth, picheight prs = Presentation() slide = prs.slides.add_slide(prs.slide_layouts[SLIDE_LAYOUT_BLANK]) pos_x = 0 pos_y = 0 k = 1 for fn in os.listdir(fd): print fn, k slide.shapes.add_picture(fd+fn,pos_x,pos_y,step_x,step_y) if reposition: pos_x += step_x if k % ncol == 0: pos_x = 0 pos_y += step_y if k % (nrow*ncol) == 0: pos_y = 0 slide = prs.slides.add_slide( prs.slide_layouts[SLIDE_LAYOUT_BLANK]) k += 1 #if and (not resize): # slide = prs.slides.add_slide(prs.slide_layouts[SLIDE_LAYOUT_BLANK]) prs.save(ppname)
def main(): prs = Presentation('template_red.pptx') title_slidelayout = prs.slidemasters[0].slidelayouts[0] slide = prs.slides.add_slide(title_slidelayout) title = slide.shapes.title subtitle = slide.shapes.placeholders[1] title.text = "Title!" subtitle.text = "subtitle" #------------------------------------------ dirs = [o for o in glob.glob('../../Run/*') if os.path.isdir(o)] print "dirs=", dirs for dir in dirs: print "\n ------ in dir ", dir, "------" psJpgs = searchPsJpgs(dir) frames = sortPsJpgs(psJpgs) for key in frames: print frames[key] if len(frames[key]) == 2: addTwoFigs(prs, frames[key][0], frames[key][1]) prs.save('printout_cfdresults.pptx')
def __call__(self, url): #parse the url url = u'http://www.nytimes.com/2015/09/13/business/at-wework-an-idealistic-startup-clashes-with-its-cleaners.html?ref=business' article = Article(url) article.download() article.html article.parse() #reducing sentences reduction = Reduction() text = article.text reduction_ratio = 0.05 reduced_text = reduction.reduce(text, reduction_ratio) #start pptx prs = Presentation() SLD_LAYOUT_TITLE_AND_CONTENT = 1 #title page title_slide_layout = prs.slide_layouts[0] slide = prs.slides.add_slide(title_slide_layout) #top image urllib.urlretrieve(str(article.top_image), "1.png") img_path = "1.png" height = Inches(2) left = Inches(3) top = Inches(5) pic = slide.shapes.add_picture(img_path, left, top, height=height) #add title title = slide.shapes.title subtitle = slide.placeholders[1] author_name = 'Xinghai Zhang' title.text = article.title subtitle.text = author_name #subpage for sentence in reduced_text: if "Advertisement" not in sentence: slide_layout = prs.slide_layouts[SLD_LAYOUT_TITLE_AND_CONTENT] slide = prs.slides.add_slide(slide_layout) shapes = slide.shapes body_shape = shapes.placeholders[1] tf = body_shape.text_frame tf.text = sentence #end page end_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(end_slide_layout) left = width = Inches(4) txBox = slide.shapes.add_textbox(left, Inches(2), width, Inches(2.5)) tf = txBox.text_frame p = tf.add_paragraph() p.text = "The End" p.font.bold = True p.font.size = Pt(50) p = tf.add_paragraph() p.text = " Thank You" p.font.size = Pt(30) prs.save('test.pptx')
def create_ppt(collection_zip,output_dir): #Unzip the collection collection_dir = collectionplan.unzip_collection(collection_zip,output_dir) #Parse the collection collection = deque() for file in os.listdir(collection_dir): full_file_path = collection_dir + '/' + file try: collection.append(metrics.read_from_json(full_file_path)) except ValueError: logging.warning("Skipping file " + file + " as it could not be parsed") continue #Used to keep track of sections previous_section = 'None' #Instantiate presentation prs = Presentation("./pptplan/Template.pptx") logging.info("Creating Presentation") #create the title slide create_title_slide(prs) #create metric slide for each metric for metric in collection: #structure is different depending on whether it was pulled using CM API library for python or directly from CM API (IE using CURL) if 'items' in metric: metric = metric['items'][0] #if an empty list, skip if len(metric['timeSeries']) == 0: logging.warning("Skipped empty metric with payload: " + str(metric)) continue #used to determine which section a metric fits in category = metric['timeSeries'][0]['metadata']['attributes']['category'] if category == 'SERVICE': service_name = metric['timeSeries'][0]['metadata']['attributes']['serviceDisplayName'] elif category == 'IMPALA_QUERY': service_name = 'IMPALA' else: service_name = 'GENERAL' #if the section is different than the last section, create a section slide if service_name.lower() != previous_section.lower(): create_section_slide(prs,service_name) previous_section = service_name #now create the slide for the metric metric_name = metric['timeSeries'][0]['metadata']['metricName'] logging.info("Creating Slide For: " + metric_name) create_metric_slide(prs,metric) #create summary slide, reccomendation slide, and ending slide create_summary_slide(prs) create_rec_slide(prs) create_end_slide(prs) #save output output_name = os.path.basename(collection_zip).split(".zip")[0] output_file = output_dir + '/' + output_name + '.pptx' logging.info("Saving presentation at location: " + output_file) prs.save(output_file)
def main(): parser = argparse.ArgumentParser( description='Create PowerPoint slides from a plain text file') parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input text file to be read' ) parser.add_argument('-o', '--output_file', type=str, required=True, help='Path to an output pptx file to be created' ) args = parser.parse_args() prs = Presentation() bullet_layout = prs.slide_layouts[1] current_slide = None current_body_shape = None current_tf = None for line in open(args.input_file): line = line.rstrip() # skip blank lines if len(line) == 0: continue if line.startswith(' '): raise Exception("Header levels greater than 3 are not supported") elif line.startswith(' '): raise Exception('Sub-headers not yet supported') elif line.startswith(' '): raise Exception('Sub-headers not yet supported') elif line.startswith('#'): hash_count = get_hash_count(line) if hash_count == 1: if current_tf is None: current_tf = current_body_shape.text_frame current_tf.text = line.lstrip('#') else: p = current_tf.add_paragraph() p.text = line.lstrip('#') p.level = hash_count - 1 elif hash_count > 1: p = current_tf.add_paragraph() p.text = line.lstrip('#') p.level = hash_count - 1 else: # Must be a title slide line current_slide = prs.slides.add_slide(bullet_layout) shapes = current_slide.shapes title_shape = shapes.title title_shape.text = line current_body_shape = shapes.placeholders[1] current_tf = None prs.save(args.output_file)
def parse_csv_file(book, chapter): csv_file_name = get_csv_file_name(book['name'], chapter) pptx_file_name = get_combo_pptx_file_name(book['name'], chapter) if not to_be_updated(csv_file_name, pptx_file_name): # Skip return prs = Presentation(os.path.join(BIBLE_COMBO_PPTX_TEMPLATE_PATH, '{0}.pptx'.format(__theme__))) title_slide_layout_large = prs.slide_layouts[0] title_slide_layout_medium = prs.slide_layouts[1] title_slide_layout_small = prs.slide_layouts[2] title_slide_layout_extra_small = prs.slide_layouts[3] with open(csv_file_name) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: chapter = row[1]; verse = row[2]; verse_content = row[3] key = book['name'] + ":" + row[1] + ":" + row[2]; if key in cu_bible: verse_cu = cu_bible[key] else: verse_cu = verse_content size = max(len(verse_content), len(verse_cu)); if size <= 84: # 6 x 7 * 2 slide = prs.slides.add_slide(title_slide_layout_large) elif size <= 144: # 8 x 9 * 2 slide = prs.slides.add_slide(title_slide_layout_medium) elif size <= 220: # 10 x 11 * 2 slide = prs.slides.add_slide(title_slide_layout_small) else: # 18 x 10 slide = prs.slides.add_slide(title_slide_layout_extra_small) title = slide.shapes.title sk_verse_content = slide.placeholders[1] cu_verse_content = slide.placeholders[10] sk_book_title = slide.placeholders[11] cu_book_title = slide.placeholders[12] title.text = u'{0} [{1}:{2}]'.format(book['title'], chapter, verse) sk_verse_content.text = verse_content cu_verse_content.text = verse_cu sk_book_title.text = book['sk_title'] cu_book_title.text = book['cu_title'] # print "{0} {1}:{2} {3}".format(row[0], row[1], row[2], row[3]) print "Creating {0}".format(pptx_file_name) prs.save(pptx_file_name)
def CreatePPT(self, song_title_list, song_dict): log.debug ("PPTProduct:CreatePPT, title:{} content:{} ".format(song_title_list, len(song_dict))) prs = Presentation("template.pptx") is_first_slide = True for title in song_title_list: song_lyric_paragraph_list = song_dict.get(title) if song_lyric_paragraph_list == None: continue for song_lyric_paragraph in song_lyric_paragraph_list: slide = "" if len(song_lyric_paragraph) > LANGEST_LINE_IN_PPT: pages = len(song_lyric_paragraph) / LANGEST_LINE_IN_PPT for index in range(0,pages): if is_first_slide == True: slide = prs.slides[0] is_first_slide = False else: empty_slide_layout = prs.slide_layouts[EMPTY_SLIDE] slide = prs.slides.add_slide(empty_slide_layout) self.AddLyric(slide, song_lyric_paragraph[ index * LANGEST_LINE_IN_PPT: (index + 1) * LANGEST_LINE_IN_PPT]) self.AddTitle(slide, title) empty_slide_layout = prs.slide_layouts[EMPTY_SLIDE] slide = prs.slides.add_slide(empty_slide_layout) self.AddLyric(slide, song_lyric_paragraph[ pages * LANGEST_LINE_IN_PPT: ]) self.AddTitle(slide, title) else: if is_first_slide == True: slide = prs.slides[0] is_first_slide = False else: empty_slide_layout = prs.slide_layouts[EMPTY_SLIDE] slide = prs.slides.add_slide(empty_slide_layout) self.AddLyric(slide, song_lyric_paragraph) self.AddTitle(slide, title) prs.save(today + '.pptx') log.debug ("PPTProduct:CreatePPT: {}.pptx is save".format(today))
class pptRep(): def __init__(self, inFile, outfile, repFile): inFile = os.path.abspath(inFile) if not os.path.isfile(inFile): exit('Input file does not exists: %s' % inFile) self.prs = Presentation(inFile) self.loadReplaceFile(repFile) self.doReplaces() self.savePres(outfile) def loadReplaceFile(self, repFile): repFile = os.path.abspath(repFile) if not os.path.isfile(repFile): exit('File with string to replace doesnot exists: %s' % repFile) self.cp = ConfigParser.ConfigParser() self.cp.read(repFile) # retrieves a configuration value from config. file or the same text if it is not found def getReplace(self, txtToReplace): # the section name does not matter. use the first if len(self.cp.sections()): section = self.cp.sections()[0] searchTxt = txtToReplace.replace('{','').replace('}','').strip() if self.cp.has_option(section, searchTxt): rep = self.cp.get(section, searchTxt) return rep return txtToReplace def savePres(self, outputFile): outputFile = os.path.abspath(outputFile) self.prs.save(outputFile) def doReplaces(self): ''' Replaces each ocurrence of text inside presentation file. ''' for slide in self.prs.slides: for shape in slide.shapes: if not shape.has_text_frame: continue for paragraph in shape.text_frame.paragraphs: for run in paragraph.runs: if '{' in run.text: if '}' in run.text: pp.pprint(run.text) # replaces if fould, leave it if not found! run.text = self.getReplace(run.text)
def make_presentation(d): title_dict, data_list = d['first'], d['slides'] #title_dict = {"title":"Go Go Slide-O-Matic", "author":"Slide-O-Matic Team", }#"image":"title_img.jpg"} #contact_dict = {"name": "The marvelous Team\nTest", "phone": "10-9", "email": "*****@*****.**"} prs = Presentation() add_title_slide(prs, title_dict) parsing_and_create_slides(prs, data_list) #add_text_slide(prs, slide1) #add_contact_slide(prs, contact_dict) prs.save('test.pptx')
def generatePptWithImages(images,filename): prs = Presentation() index = 0 for img in images: if os.path.isfile(img): index = index + 1 if index > 10: break size = changeSize(getImageSize(img)) lt = getLeftAndTop(size) blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) pic = slide.shapes.add_picture(img,getInches(lt[0]),getInches(lt[1]),width=getInches(size[0]),height=getInches(size[1])) prs.save(ppt_path + filename + ppt_file) return 1
def get_ppt(self): prs = Presentation() blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) self.fc.print_png("/tmp/test.png", transparent=True) left = Inches(0) top = Inches(1.5) pic = slide.shapes.add_picture("/tmp/test.png", left, top) file_path = '/tmp/test.pptx' prs.save(file_path) fsock = open(file_path,"r") response = HttpResponse(fsock, content_type='application/vnd.openxmlformats-officedocument.presentationml.presentation') response['Content-Disposition'] = 'attachment; filename=TestPpt.pptx' #fc.print_png(response) return response
def create_presentation(output, texts, master_slide, font_color): # Here is exponential regression to fit character without hyphenation def estimate_font_size(str_length): a = 31.52805 b = 266.4258 c = 0.091539 pt = floor(a + b*exp(-c*str_length)) if pt < 32: return 32 if pt > 200: return 200 return pt def estimate_max_length(text): return max([len(x) for x in text]) def prepare_text(text): return '\n'.join(text) def decorate_shape(shape, text, font_color): run = shape.text_frame.paragraphs[0].add_run() run.font.size = Pt(estimate_font_size(estimate_max_length(text))) run.text = prepare_text(text) if font_color == 'white': color = RGBColor(255, 255, 255) else: color = RGBColor(0, 0, 0) run.font.color.rgb = color def create_slide(slide, text, font_color): shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, 0, PRESENTATION_WIDTH, PRESENTATION_HEIGHT) shape.fill.background() shape.line.color.rgb = RGBColor(0, 0, 0) decorate_shape(shape, text, font_color) p = Presentation(master_slide) for i, text in enumerate(texts): if i == 0: slide = p.slides[0] else: slide = p.slides.add_slide(p.slide_layouts[11]) create_slide(slide, text, font_color) p.save(output)
def merge(pres): #open p1 and p2; merge prs = Presentation() img_path = 'logo.png' for each in pres: p = Presentation(pres) for slide in p.slides: prs.slides.add_slide(slide) #add each slide to main presentation #add divider slide slide = prs.slides.add_slide(prs.slide_layouts[6]) #blank slide left = top = Inches(1) height = Inches(5.5) pic = slide.shapes.add_picture(img_path, left, top, height=height) prs.save('gm.pptx') return prs
def make_pptx(texts): prs = Presentation() for text in texts: blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) txBox = slide.shapes.add_textbox(0, 0, Cm(25.4), Cm(19.1)) tf = txBox.textframe tf.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE tf.word_wrap = True tf.vertical_anchor = MSO_ANCHOR.MIDDLE p = tf.paragraphs[0] p.text = text p.font.size = Pt(find_best_fontsize(text)) p.alignment = PP_ALIGN.CENTER prs.save('test.pptx')
def main(argv): inputTemplate = '' inputCSV = '' try: opts, args = getopt.getopt(argv,"hi:c:",["ifile=","cfile="]) except getopt.GetoptError: print 'generate_bib.py -i <input_ppt_template> -c <input_CSV>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'generate_bib.py -i <input_ppt_template> -c <input_CSV>' sys.exit() elif opt in ("-i", "--ifile"): inputTemplate = arg elif opt in ("-c", "-cfile"): inputCSV = arg print("Generating bibs using base powerpoint template : " + inputTemplate + "and csv file " + inputCSV) # Open a presentation f = open(inputTemplate) prs = Presentation(f) f.close() # Open CSV file csv_in = open(inputCSV) participants = csv.DictReader(csv_in, delimiter=',') # Get the templated slide layout slide_layout = prs.slide_layouts[1] # for every CSV entry for line in participants: print(line["Bib"], line["Name"], line["Category"]) # Add new slide slide = prs.slides.add_slide(slide_layout) for shape in slide.placeholders: #print('%d %s' % (shape.placeholder_format.idx, shape.name)) if shape.placeholder_format.idx == 11: shape.text = line["Category"] elif shape.placeholder_format.idx == 12: shape.text = line["Name"] elif shape.placeholder_format.idx == 13: shape.text = line["Bib"] prs.save('generated_bibs.pptx')
def create_ppt(self): self.log.info('Called create_ppt') prs = Presentation() try: for slide_number in range(self.total_pages): img_path = self.pdf_file.replace('.pdf', '_%s%s' % (str(slide_number+1), '.jpg')) self.log.debug('%s' % img_path) new_slide = prs.slide_layouts[0] slide = prs.slides.add_slide(new_slide) subtitle = slide.placeholders[1] title = slide.shapes.title title.text = "Image %s " % str(slide_number+1) left = top = Inches(0.1) height = Inches(7.5) pic = slide.shapes.add_picture(img_path, left, top, height=height) prs.save(self.ppt_file) except IOError: self.log.error('error creating ppt', exc_info=True)
def pres(): pres = Presentation() # layout layout_1 = pres.slide_layouts[0] # Slide slide = pres.slides.add_slide(layout_1) # Mek shape shape = slide.shapes # title title = shape.placeholders[0] title.text = 'Practice' pres.save('practice.pptx')
def jpgListToPowerpoint(jpgList,savePath): #slide dimensions are in inches slideWidth = 720 #dimensions are @96DPI, default for pptx library slideHeight = 540 emuPixelRatio = 12700 if not type(jpgList) is list: print "jpgList in jpgListToPowerpoint is not a list" sys.exit(1) prs = Presentation() for jpgPath in jpgList: blank_slidelayout = prs.slidelayouts[6] slide = prs.slides.add_slide(blank_slidelayout) (picX,picY) = Image.open(jpgPath).size (x, y, cx, cy) = getDimensions(picX,picY,slideWidth,slideHeight,emuPixelRatio) #print (picX,picY),(x, y, cx, cy) #bug: scaled pictures don't show up in presentation - check documentation pic = slide.shapes.add_picture(jpgPath, x, y, cx, cy) print "Saving..." prs.save(savePath)
def generate_template_from_source_ppt(self): # Create a ppt based on template prs = Presentation(self.PPT_SOURCE) # Iterating through each layout present in the file # Different PPT files have different number of layouts # "__" is used for unnecessary variables that are not used anywhere for layout_index, __ in enumerate(prs.slide_layouts): # define a slide layout slide_layout = prs.slide_layouts[layout_index] # Assign the layout to a slide slide = prs.slides.add_slide(slide_layout) # Once a slide is created, everything else is done through "shapes" # Shapes behave the same way as a list # Assign the layout name as the slide title # Some slide layouts do not have slide title shape if(slide.shapes.title is not None): slide.shapes.title.text = slide_layout.name # Find out how many objects are present in the slide to playwith print("There are {0} shapes and {1} placeholders in the slide layout {2}".format(len(slide.shapes), len(slide.placeholders), slide_layout.name)) # Iterate over the placeholders in the slide # "__" is used for unnecessary variables that are not used anywhere for placeholder_index, __ in enumerate(slide.shapes): # If the placeholder is not the slide title, then update it with placeholder type if(slide.shapes[placeholder_index].has_text_frame): # The name for title placeholder is always "Title 1", title placeholder is already populated with layout name; so skip if not(slide.shapes[placeholder_index].name in "Title 1"): slide.shapes[placeholder_index].text = slide.shapes[placeholder_index].name # Finally save the presentation prs.save(self.GENERATED_TEMPLATE_PPT) print("Done. {0} slide(s) added".format(len(prs.slides))) return self.GENERATED_TEMPLATE_PPT
def download(self, instance): prs = Presentation('template.pptx') # Left, top, width, height for i in range(0, len(download_identifiers)): if i == 0 or i % 2 == 1: slide = prs.slides[-1] else: slide = prs.slides.add_slide(prs.slide_layouts[1]) # Details if i % 2 == 1: tx_box1 = slide.shapes.add_textbox(Inches(5.2), Inches(5.5), Inches(4.5), Inches(2)) else: tx_box1 = slide.shapes.add_textbox(Inches(0.5), Inches(5.5), Inches(4.5), Inches(2)) tf1 = tx_box1.text_frame tf1.word_wrap = True run = tf1.paragraphs[0].add_run() run.text = download_details[i] run.font.size = Pt(14) # Stats if i % 2 == 1: tx_box2 = slide.shapes.add_textbox(Inches(5.2), Inches(4.2), Inches(4.5), Inches(2)) else: tx_box2 = slide.shapes.add_textbox(Inches(0.5), Inches(4.2), Inches(4.5), Inches(2)) tf2 = tx_box2.text_frame tf2.word_wrap = True run = tf2.paragraphs[0].add_run() run.text = download_stats[i] run.font.size = Pt(14) # Graph if i % 2 == 1: slide.shapes.add_picture(download_images[i], Inches(4.8), Inches(1.2), height=Inches(3.0), width=Inches(5.0)) else: slide.shapes.add_picture(download_images[i], Inches(0.1), Inches(1.2), height=Inches(3.0), width=Inches(5.0)) date = datetime.datetime.now().strftime("%m-%d-%Y") prs.save(PATH[:-8] + "\\output\\" + date + '.pptx') del download_identifiers[:] del download_images[:] del download_details[:] del download_stats[:] self.update()
def createprez(btn): print("presentation being built") songs = [] #read songs from files for path in app.getAllListItems("list_out"): songs.extend(open(mypath+"/"+path, "r").readlines()); prs = Presentation("./template.pptx") bullet_slide_layout = prs.slide_layouts[5] slide = prs.slides.add_slide(bullet_slide_layout) shapes = slide.shapes body_shape = shapes.placeholders[0] tf = body_shape.text_frame p = tf.paragraphs[0] p.alignment = PP_ALIGN.CENTER for song in songs: if(song != '\n'): print(song) p.text += song; else: bullet_slide_layout = prs.slide_layouts[5] slide = prs.slides.add_slide(bullet_slide_layout) shapes = slide.shapes body_shape = shapes.placeholders[0] tf = body_shape.text_frame p = tf.paragraphs[0] p.alignment = PP_ALIGN.CENTER name = file_name+time.strftime("%Y-%m-%d")+".pptx" prs.save(name) print(name+" mentve")
def TestCreatePPT(self): log.debug ("PPTProduct:TestCreatePPT") prs = Presentation("template.pptx") title_slide_layout = prs.slide_layouts[DEFAULT_SLIDE] slide = prs.slides.add_slide(title_slide_layout) title = slide.shapes.title shapes = slide.shapes subtitle = slide.placeholders[1] title.text = "Hello, World!\n test\n test\n" subtitle.text = "python-ppt was here!" # left = top = width = height = Cm(8.0) # slide.shapes.add_shape( # MSO_SHAPE.ROUNDED_RECTANGLE, left, top, width, height # ) prs.save('test.pptx') log.debug ("PPTProduct:TestCreatePPT: test.ppt is save")
def get_ppt(self, request, objects): user = None if request.user.is_authenticated(): user = request.user else: return if objects and len(objects) > 0: gttg_obj = objects[0] prs = Presentation(CFG_GTTG_POWERPOINT_TEMPLATE) self.make_ppt_title_page(prs, gttg_obj) self.make_ppt_toc(prs, gttg_obj) self.make_ppt_intro(prs, gttg_obj) self.make_ppt_topics(prs, gttg_obj) self.make_ppt_audience(prs, gttg_obj) self.make_ppt_last_page(prs, gttg_obj) output = BytesIO() prs.save(output) response = HttpResponse(output.getvalue(), content_type='application/vnd.openxmlformats-officedocument.presentationml.presentation') response['Content-Disposition'] = 'attachment; filename="gttg.pptx"' response['Content-Length'] = output.tell() return response
from pptx import Presentation from csv_loader import srednia prs = Presentation() slide_layout = prs.slide_layouts[1] slide = prs.slides.add_slide(slide_layout) shapes = slide.shapes title_shape = shapes.title body_shape = shapes.placeholders[1] title_shape.text = 'Jakis text' tf = body_shape.text_frame tf.text = 'Zawartosc text frame' p = tf.add_paragraph() p.text = "Kobiety - srednia wieku" p.level = 1 p = tf.add_paragraph() p.text = f"{srednia()}" p.level = 2 prs.save("raport.pptx")
def generate_ppt(): paths=[] result=request.args.get('input') arguments={"keywords": result,"limit":5} response=google_images_download.googleimagesdownload() paths.append(response.download(arguments)) img1= paths[0][arguments['keywords']][0] prs=Presentation() slide_layout1=prs.slide_layouts[0] slide1=prs.slides.add_slide(slide_layout1) shapes=slide1.shapes left_pic=Inches(0) top_pic=Inches(0) width_pic=Inches(3) height_pic=Inches(7.5) pic=slide1.shapes.add_picture(img1,left_pic,top_pic,width_pic,height_pic) placeholder_title=slide1.placeholders[0] placeholder_title.left=Inches(3.3) placeholder_title.top=Inches(0.5) placeholder_title.width=Inches(6) placeholder_title.height=Inches(2) placeholder_content=slide1.placeholders[1] placeholder_content.left=Inches(3.4) placeholder_content.top=Inches(4) placeholder_content.width=Inches(6) placeholder_content.height=Inches(2.3) slide_layout2=prs.slide_layouts[0] slide2=prs.slides.add_slide(slide_layout1) shapes=slide2.shapes left_pic=Inches(0) top_pic=Inches(0) width_pic=Inches(3) height_pic=Inches(7.5) img2= paths[0][arguments['keywords']][1] pic=slide2.shapes.add_picture(img2,left_pic,top_pic,width_pic,height_pic) placeholder_title=slide2.placeholders[0] placeholder_title.left=Inches(3.3) placeholder_title.top=Inches(0.5) placeholder_title.width=Inches(6) placeholder_title.height=Inches(2) placeholder_content=slide2.placeholders[1] placeholder_content.left=Inches(3.4) placeholder_content.top=Inches(4) placeholder_content.width=Inches(6) placeholder_content.height=Inches(2.3) slide_layout3=prs.slide_layouts[0] slide3=prs.slides.add_slide(slide_layout1) shapes=slide3.shapes left_pic=Inches(0) top_pic=Inches(0) width_pic=Inches(3) height_pic=Inches(7.5) img3= paths[0][arguments['keywords']][2] pic=slide3.shapes.add_picture(img3,left_pic,top_pic,width_pic,height_pic) placeholder_title=slide3.placeholders[0] placeholder_title.left=Inches(3.3) placeholder_title.top=Inches(0.5) placeholder_title.width=Inches(6) placeholder_title.height=Inches(2) placeholder_content=slide3.placeholders[1] placeholder_content.left=Inches(3.4) placeholder_content.top=Inches(4) placeholder_content.width=Inches(6) placeholder_content.height=Inches(2.3) slide_layout4=prs.slide_layouts[0] slide4=prs.slides.add_slide(slide_layout1) shapes=slide4.shapes left_pic=Inches(0) top_pic=Inches(0) width_pic=Inches(3) height_pic=Inches(7.5) img4= paths[0][arguments['keywords']][3] pic=slide4.shapes.add_picture(img4,left_pic,top_pic,width_pic,height_pic) placeholder_title=slide4.placeholders[0] placeholder_title.left=Inches(3.3) placeholder_title.top=Inches(0.5) placeholder_title.width=Inches(6) placeholder_title.height=Inches(2) placeholder_content=slide4.placeholders[1] placeholder_content.left=Inches(3.4) placeholder_content.top=Inches(4) placeholder_content.width=Inches(6) placeholder_content.height=Inches(2.3) slide_layout5=prs.slide_layouts[0] slide5=prs.slides.add_slide(slide_layout1) shapes=slide5.shapes left_pic=Inches(0) top_pic=Inches(0) width_pic=Inches(3) height_pic=Inches(7.5) img5= paths[0][arguments['keywords']][4] pic=slide5.shapes.add_picture(img5,left_pic,top_pic,width_pic,height_pic) placeholder_title=slide5.placeholders[0] placeholder_title.left=Inches(3.3) placeholder_title.top=Inches(0.5) placeholder_title.width=Inches(6) placeholder_title.height=Inches(2) placeholder_content=slide5.placeholders[1] placeholder_content.left=Inches(3.4) placeholder_content.top=Inches(4) placeholder_content.width=Inches(6) placeholder_content.height=Inches(2.3) prs.save("result.pptx") print("file saved") return send_file('result.pptx',as_attachment=True)
def write(file_names, cmsw): """Writes data into the an Excel Sheet and a Power Point slide as seen in the example Takes two inputs: -the file names of the CMSW databases -the serial numbers of the CMSWs Generates two files: -The summary table -The Power Point slide, which was copied from the example """ print('Processing data for sales report') cases = list_builder(file_names) cases.append(('', '', '', '', '', '', '', '', '', '')) cases.append(('', '', 'Excluded Cases (not included in above summary)', '', '', '', '', '', '', '')) xlsx_name = str(cmsw) + '-data-tables.xlsx' wb = openpyxl.load_workbook('Sales-Template.xlsx') data_sheet = wb.active data_sheet.title = 'Sheet1' print('Data ready, writing sales report') line = 17 total_attempted = 0 total_to_patient = 0 total_diverted = 0 number_of_cases = -2 for row in range(len(cases)): if cases[row][8] == '': number_of_cases += 1 if not cases[row][4] == '': total_attempted += float(cases[row][4]) total_to_patient += float(cases[row][5]) total_diverted += float(cases[row][6]) for col in range(len(cases[row])): data_sheet.cell(row=line, column=col + 1, value=cases[row][col]) data_sheet.cell(row=line, column=col + 1).alignment = Alignment(wrapText=True) if row == len(cases) - 1: data_sheet.cell(row=line, column=2).font = Font(bold=True) line += 1 data_sheet.cell(row=line - 1, column=3).alignment = Alignment(wrapText=False) data_sheet.cell(row=line - 1, column=3).font = Font(bold=True, size=16) data_sheet.cell(row=6, column=5, value=total_attempted) data_sheet.cell(row=6, column=5).alignment = Alignment(wrapText=True, horizontal='center') data_sheet.cell(row=6, column=6, value=total_to_patient) data_sheet.cell(row=6, column=6).alignment = Alignment(wrapText=True, horizontal='center') data_sheet.cell(row=6, column=7, value=total_diverted) data_sheet.cell(row=6, column=7).alignment = Alignment(wrapText=True, horizontal='center') exclusions = [ 'Exclusion criteria include', '1. Case duration < 5 mins', '2. 0 mL contrast injected', '3. DyeTect cases', '4. Diverted Vol < 5 mL', '5. Attempted Vol < 20 mL' ] cases.append(('', '', '', '', '', '', '', '', ' ', '')) for exclusion in exclusions: cases.append(('', '', '', '', '', '', '', '', exclusion, '')) for row in range(len(cases)): if not cases[row][8] == '': for col in range(len(cases[row])): data_sheet.cell(row=line, column=col + 1, value=cases[row][col]) data_sheet.cell(row=line, column=col + 1).alignment = Alignment(wrapText=True) data_sheet.cell(row=line, column=1, value='') data_sheet.cell(row=line, column=1).alignment = Alignment(wrapText=True) line += 1 data_sheet.column_dimensions['A'].hidden = True wb.save(xlsx_name) pptx_name = str(cmsw) + '-slide.pptx' colors = [0, 0, 0, 0] attempted = 0 diverted = 0 print('Report written, constructing slide') for case in cases: if case[8] == '': if case[0] == RED: colors[0] += 1 elif case[0] == YELLOW: colors[1] += 1 elif case[0] == GREEN: colors[2] += 1 elif case[0] == LIGHT_GREEN: colors[3] += 1 if not case[4] == '': attempted += float(case[4]) diverted += float(case[6]) percent_saved = round(diverted / attempted * 100) prs = Presentation('Slide-Template.pptx') total = colors[0] + colors[1] + colors[2] + colors[3] title = 'N=' + str(total) data = CategoryChartData() data.add_series(title, colors) data.categories = [ '> Threshold, N=', '< Threshold, N=', '< 2/3 Threshold, N=', '< 1/3 Threshold, N=' ] prs.slides[0].shapes[4].chart.replace_data(data) text = [ 'All cases (N=' + str(number_of_cases) + ')', str(percent_saved) + '% avg \nLess \nContrast', str(round(diverted)) + ' mL less total' ] for box in range(5, 8, 1): prs.slides[0].shapes[box].text_frame.clear() prs.slides[0].shapes[box].text_frame.paragraphs[0].text = text[box - 5] prs.slides[0].shapes[box].text_frame.paragraphs[ 0].allignment = PP_ALIGN.CENTER prs.slides[0].shapes[box].text_frame.paragraphs[0].font.size = Pt(26 - 2 * box) prs.slides[0].shapes[5].text_frame.paragraphs[0].font.bold = True prs.slides[0].shapes[7].text_frame.paragraphs[0].font.italic = True prs.save(pptx_name) print('Slides complete')
# Loop over slides for i, slideimg in enumerate(slideimgs): if i % 10 == 0: print("Saving slide: " + str(i)) imagefile = BytesIO() slideimg.save(imagefile, format='jpeg') imagedata = imagefile.getvalue() imagefile.seek(0) width, height = slideimg.size # Set slide dimensions prs.slide_height = height * 9525 prs.slide_width = width * 9525 # Add slide slide = prs.slides.add_slide(blank_slide_layout) pic = slide.shapes.add_picture(imagefile, 0, 0, width=width * 9525, height=height * 9525) # Save Powerpoint print() print("Saving file: " + base_name + ".pptx") prs.save(base_name + '.pptx') print("Conversion complete. :)") print()
def convert_file_for_pptx(out_filename, template_file, ds_dict): '''按模板转换xlsx文件 按字典转换模板文件,输出为out_filename ''' unzip_path = os.path.join(out_filename + 't\\pptx_tmp') if (os.path.exists(unzip_path)): shutil.rmtree(unzip_path) unzip_single(template_file, unzip_path) embeddings_path = os.path.join(unzip_path, "ppt\\embeddings") tmp_pd_dict = {} tmp_excel_active_sheet_dict = {} if (os.path.exists(embeddings_path)): for x in os.listdir(embeddings_path): if x.endswith('.xlsx'): active_name = convert_file_for_xlsx( os.path.join(embeddings_path, x), os.path.join(embeddings_path, x), ds_dict, outImage=False) tmp_excel_active_sheet_dict[x] = active_name tmp_pd_dict[x] = pd.read_excel(os.path.join( embeddings_path, x)) xlsx_emf_arr = [] root_path = os.path.join(unzip_path, "ppt") for slide in os.listdir(f"{root_path}\slides"): if slide.endswith(".xml") == False: continue doc = lxml.etree.XML( open(f"{root_path}\\slides\\{slide}", 'rb').read()) id_embed_dict = {} for one_oleObj in doc.xpath("//p:oleObj", namespaces=doc.nsmap): for one_blip in one_oleObj.xpath(".//a:blip", namespaces=doc.nsmap): id = one_oleObj.attrib.get('{' + doc.nsmap['r'] + '}id') embed = one_blip.attrib.get('{' + doc.nsmap['r'] + '}embed') id_embed_dict[id] = embed if len(id_embed_dict) > 0: rels = lxml.etree.XML( open(f"{root_path}\\slides\_rels\\{slide}.rels", 'rb').read()) for id, embed in id_embed_dict.items(): xlsx = rels.xpath( f"//*[local-name() = 'Relationship'][@Id='{id}'] " )[0].attrib['Target'] emf = rels.xpath( f"//*[local-name() = 'Relationship'][@Id='{embed}'] " )[0].attrib['Target'] xlsx_emf_arr.append({"xlsx": xlsx, "emf": emf, "slide": slide}) for one in xlsx_emf_arr: png_file = os.path.realpath(root_path + "/slides/" + one['xlsx'] + "1.png") emf_file = os.path.realpath(root_path + "/slides/" + one['emf']) excel2img.export_img( root_path + "/slides/" + one['xlsx'], png_file, tmp_excel_active_sheet_dict[one['xlsx'].split("/")[-1]]) my_cmd = f'convert "{png_file}" "{emf_file}"' cmd_output = os.popen(my_cmd).readlines() os.remove(png_file) zipDir(unzip_path, out_filename) shutil.rmtree(out_filename + "t") env = get_jinja2_Environment() ppt_file = Presentation(out_filename) ''' #expr title_lines=1 loop_var=index,row dataset=a.sort_values(zhibiao,ascending=False)[:size] ''' def calc_frame_txt(obj, calc_dict, calc_kind=None): if calc_kind is None: calc_kind = 1 if len(obj.text_frame.paragraphs) < 1 else 3 if calc_kind == 3: #text_frame 中有多个不同格式的文本,需要查runs,通常不应该是这样的 for paragraph in obj.text_frame.paragraphs: exp_list = [] if paragraph.text.find('{{') > -1: start, end, s_num, e_num = -1, -1, 0, 0 for idx, run in enumerate(paragraph.runs): if run.text.find('{{') > -1: s_num += 1 if s_num == 1: start = idx if run.text.find('}}') > -1: end = idx e_num += 1 if start >= 0 and end >= 0 and s_num == e_num: exp_list.append((start, end)) start, end, s_num, e_num = -1, -1, 0, 0 for start, end in exp_list: if start >= 0 and end >= 0 and start <= end: text = ''.join([ x.text for x in paragraph.runs[start:end + 1] ]) try: result = exec_template(env, text, calc_dict) except Exception as e: raise RuntimeError(text) paragraph.runs[start].text = result for x in paragraph.runs[start + 1:end + 1]: x.text = '' elif calc_kind == 2: for paragraph in obj.text_frame.paragraphs: if paragraph.text.find('{{') > -1: try: result = exec_template(env, paragraph.text, calc_dict) except: raise RuntimeError(paragraph.text) for run in paragraph.runs: run.text = '' #直接copy font 报错,我们通过将其他runs中的文字清空,计算出的新文字赋值给第一个run。这样就保留了格式 paragraph.runs[0].text = result else: expr = obj.text_frame.text if expr.find('{{') > -1: try: result = exec_template(env, expr, calc_dict) # env.from_string(expr) except: raise RuntimeError(paragraph.text) for paragraph in obj.text_frame.paragraphs: for run in paragraph.runs: run.text = '' #直接copy font 报错,我们通过将其他runs中的文字清空,计算出的新文字赋值给第一个run。这样就保留了格式 obj.text_frame.paragraphs[0].runs[0].text = result def handle_all_shapes(shapes, real_dict, tmp_pd_dict): # real_dict 我们使用这个参数来层层传递外面定义变量 #tmp_pd_dict 是专为内嵌excel准备的,貌似递归取不到外层定义的变量 for shape in shapes: #shape.part.related_parts['rId4'].blob if hasattr(shape, "shapes"): handle_all_shapes(shape.shapes, real_dict, tmp_pd_dict) continue if shape.has_text_frame or shape.has_table: pass if shape.shape_type == MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT: pass if shape.has_text_frame: calc_frame_txt(shape, real_dict) elif shape.has_chart: key = shape.chart._workbook.xlsx_part.partname.split("/")[-1] # 定义图表数据 --------------------- chart_data = ChartData() columns = list(tmp_pd_dict[key].columns.values) chart_data.categories = tmp_pd_dict[key][columns[0]] for one in columns[1:]: chart_data.add_series(one, tuple(tmp_pd_dict[key][one])) shape.chart.replace_data(chart_data) elif shape.has_table: current_row = 0 for row in shape.table.rows: current_col = 0 for cell in row.cells: if cell.text_frame.text.find('{{') < 0: current_col = current_col + 1 continue try: result = exec_template(env, cell.text_frame.text, real_dict) except: raise RuntimeError(cell.text_frame.text) for paragraph in cell.text_frame.paragraphs: for run in paragraph.runs: run.text = '' #直接copy font 报错,我们通过将其他runs中的文字清空,计算出的新文字赋值给第一个run。这样就保留了格式 copy_row = current_row result_lines = result.split('\n') for one_line in result_lines: #展开模板计算结果 copy_col = current_col #从当前位置开始,复制结果到ppt的table中 for one in one_line.split(): cur_row_cells = shape.table.rows[ copy_row].cells if copy_col >= len( cur_row_cells ): #如果ppt table 中的列不够用,当前行的复制就结束 break p_cell = cur_row_cells[copy_col] if len(p_cell.text_frame.paragraphs[0].runs ) == 0: p_cell.text_frame.paragraphs[0].add_run() p_cell.text_frame.paragraphs[0].runs[ 0].text = one copy_col = copy_col + 1 copy_row = copy_row + 1 if copy_row >= len(shape.table.rows): #行不够就结束复制 break current_col = current_col + 1 current_row = current_row + 1 if current_row >= len(shape.table.rows): break try: real_dict = ds_dict.copy() for slide in ppt_file.slides: if slide.has_notes_slide: #抽取备注栏里面的变量定义,后页会覆盖前页 notes_text = slide.notes_slide.notes_text_frame.text for one_line in notes_text.split("\n"): var_expr = one_line.split("=") if len(var_expr) < 2: continue try: if var_expr[1].strip().startswith("{{"): result_lines = exec_template( env, var_expr[1], real_dict) else: result_lines = exec_template( env, "{{" + var_expr[1] + "}}", real_dict) real_dict = real_dict.copy() real_dict[var_expr[0].strip()] = result_lines except Exception as e: raise RuntimeError("\n备注说明中的公式不正确:" + one_line) handle_all_shapes(slide.shapes, real_dict, tmp_pd_dict) ppt_file.save(out_filename) finally: if ppt_file is not None: ppt_file.save(out_filename) del ppt_file ppt2png(out_filename, ds_dict.get("_idx_", ''))
font.color.rgb = RGBColor(0x00, 0x00, 0x00) shape.line.width = Pt(1) #shape.line.color.rgb = RGBColor(0x00, 0x00, 0x00) shape.fill.background() def connect(shape0, shape1): edge = slide.shapes.add_connector(MSO_CONNECTOR.CURVE, 0, 0, 0, 0) edge.begin_connect(shape0, 3) edge.end_connect(shape1, 1) #edge.color.rgb = RGBColor(0x00, 0x00, 0x00) node0 = slide.shapes.add_shape( MSO_SHAPE.OVAL, xs/10*0 + x0, ys/10*2 + y0, xs/10*1, ys/10*1 ) set_style(node0, "node0") label = slide.shapes.add_shape( MSO_SHAPE.RECTANGLE, xs/10*2 + x0, ys/10*4 + y0, xs/10*1, ys/10*1 ) set_style(label, "label") node1 = slide.shapes.add_shape( MSO_SHAPE.OVAL, xs/10*4 + x0, ys/10*2 + y0, xs/10*1, ys/10*1 ) set_style(node1, "node1") connect(node0, label) connect(label, node1) prs.save('test.pptx')
slide = prs.slides.add_slide(title_slide_layout) # 取本页ppt的title,向title文本框写如文字 title = slide.shapes.title title.text = '箱线图示例' # 导入数据集 df = pd.read_excel('./resource/data0.xlsx', 'Sheet1') # 保存箱线图 fig = plt.figure() ax = fig.add_subplot(111) ax.boxplot(df['交付周期']) plt.savefig('./resource./交付周期_箱线图.png') plt.show() # 插入图片,在指定位置按预设值添加图片 img_path = './resource./交付周期_箱线图.png' left, top, width, height = Inches(1), Inches(1.8), Inches(4.5), Inches(4.5) slide.shapes.add_picture(img_path, left, top, width, height) if __name__ == "__main__": # 使用自定义模板 prs = Presentation('./template/ppt_template0.pptx') test_slide_layout(prs) # 保存ppt prs.save('数据分析报告.pptx')
slides = prs.slides # replace text i = 0 for slide_index in range( start - 1, end - 2 ): # end-2 because the slide between hymns is empty and would result in out of range error slide = slides[slide_index] #print(slide_index) i = i + 1 #slide = slides[0] shape = slide.shapes[0] # always the 0th shape if shape.has_text_frame: text_frame = shape.text_frame #print(len(text_frame.paragraphs)) text = text_frame.paragraphs[0].text # only ever one paragraph #print('FANCY TEXT: ', text) shape.text = hymn_text[i][0] # more silliness with list in lists text = text_frame.paragraphs[0].text #print('FANCY TEXT neu: ', text) else: print('NO TEXT') if len(slides) != NUM_OF_SLIDES: print( '!!! WARNING !!! Number of slides changed, not saving!!! Current: {}, Should: {}' .format(len(slides), NUM_OF_SLIDES)) else: prs.save(ABS_PATH)
def main(): if args.input is not None: signCount = 0 callCount = 0 prs = Presentation() title_slide_layout = prs.slide_layouts[0] content_slide_layout = prs.slide_layouts[1] title_slide = prs.slides.add_slide(title_slide_layout) content_slide = [] nn = 2 if args.pages is None: print("pages flag should be number.") sys.exit(1) for i in range(int(args.pages) - 1): content_slide.append(prs.slides.add_slide(content_slide_layout)) n = int(len(content_slide)) if nn == int(args.pages): count = list(range(n)) nn = nn + 1 else: nn = nn + 1 title = title_slide.shapes.title subtitle = title_slide.placeholders[1] draft, f = inputFileRead(str(args.input)) while draft: fileContent = str(draft.strip()) if "###" in fileContent: title.text = str(fileContent.replace("###", "")) prs.save(outfilename) elif "***" in fileContent: subtitle.text = str(fileContent.replace("***", "")) prs.save(outfilename) elif "--------" in fileContent: callCount = callCount + 1 if args.pages <= 1: pass else: if callCount > 1: PCDraft = signCount + 1 signCount = signCount + 1 else: PCDraft = 0 elif "%%%" in fileContent: try: content_title = content_slide[PCDraft].shapes.title content_title.text = str(fileContent.replace("%%%", "")) except (IndexError): print("Pages is not equal to section in draft file.", "exiting...") sys.exit(1) except (UnboundLocalError): print("Slide did not have content pages but the draft ", "file specify one. Existing.") sys.exit(1) prs.save(outfilename) elif "p>" in fileContent: try: content_con = content_slide[PCDraft].shapes.placeholders[1] content_con.text = str(fileContent.replace("p>", "")) except (IndexError): print("Pages is not enough. exiting...") sys.exit(1) prs.save(outfilename) elif "bgcl>" in fileContent: background = content_slide[PCDraft].background try: R, G, B = str(fileContent.replace("bgcl>", "")).split(",") except (ValueError): print("background value should be RGB value seperate ", "by comma. Example: bgcl>255,255,255") sys.exit(1) fill = background.fill fill.solid() try: fill.fore_color.rgb = RGBColor(int(R), int(G), int(B)) except (ValueError): print("background value should be RGB value seperate by ", "comma. Example: bgcl>255,255,255") sys.exit(1) prs.save(outfilename) elif "img>" in fileContent: con_shapes = content_slide[PCDraft].shapes try: imgpath, x1, y1, x2, y2 = str( fileContent.replace("img>", "")).split(",") except (ValueError): print("image value should be image path, Position of ", "image horizontal, Position of image verticle, ", "size of image horizontal, size of image verticle.") sys.exit(1) try: con_shapes.add_picture(str(imgpath), Inches(int(x1)), Inches(int(y1)), Inches(int(x2)), Inches(int(y2))) except (ValueError): print("image value should be image path, Position of ", "image horizontal, Position of image verticle, ", "size of image horizontal, size of image verticle.") sys.exit(1) except (FileNotFoundError): print("image file did not exist. Please try again.") sys.exit(1) prs.save(outfilename) elif "\n" or "\r\n" in fileContent: pass else: print("draft file is corrupted. Check the format.txt file ", "and try again!") draft = f.readline() else: parser.print_help()
class PptxConstructor: def __init__(self, config): self.config = config self.presentation = Presentation() self.presentation.slide_width = config['prs_width'] self.presentation.slide_height = config['prs_height'] self.prs_object_pool = {} self.page_stack = {0: []} def add_object(self, data, object_type: str, object_format=None, slide_page=None, position=None): # assure the object type is text, chart, or table assert (object_type == 'text') or (object_type == 'chart') or (object_type == 'table') if position is not None: # three types of position representation: # 1. absolute position ("a", x, y, w, h) # 2. relative position to boundary ("rb", x%, y%, w%, h%) # 3. relative position to object ("rr/rl/ru/rd", uid, x, y, w, h) # assure the location is in the format of three assert isinstance(position, tuple) assert position[0] in ['a', 'rb', 'rr', 'ru', 'rl', 'rd'] if slide_page is None: # if no slide_page is given, create a new slide directly # TODO: slide_page can be str or int, but if string how to determine choose the page number slide_page = max(self.page_stack) + 1 self.page_stack[slide_page] = [] if slide_page not in self.page_stack: self.page_stack[slide_page] = [] # TODO: In the future, uid is produced by a hashmap based on the object argument. # If an object already exists, then the ObjectContainer can be reused to save space. # Currently do not apply this since no mechanism to handle duplicate objects with different location. uid = f"{object_type}_{len(self.prs_object_pool)}" ObjectContainer = namedtuple("obj", [ 'uid', 'data', "obj_type", "obj_format", "slide_page", 'position' ]) self.prs_object_pool[uid] = ObjectContainer(uid, data, object_type, object_format, slide_page, position) self.page_stack[slide_page].append(uid) return uid def pptx_execute(self): layout_designer = pptx_layout.PrsLayoutDesigner( self.config, self.prs_object_pool, self.page_stack) layout_designer.execute() design_structure = layout_designer.layout_design_export() data_processor = data_preprocessor.DataProcessor(self.prs_object_pool) data_container = data_processor.data_container_export() layout_manager = pptx_layout.PrsLayoutManager( presentation=self.presentation, object_stack=self.prs_object_pool, layout_design_container=design_structure, data_container=data_container) result = layout_manager.layout_execute() return result def pptx_save(self, filepath='C://Users/user/Desktop/untitled.pptx'): self.presentation.save(filepath) print(f"INFO: presentation file is saved successfully as {filepath}") def _set_presentation_size(self, width, height): self.presentation.slide_width = width self.presentation.slide_height = height def _presentation_reset(self): self.presentation = Presentation() self._set_presentation_size(Inches(13.33), Inches(7.5))
space_Col = 1.5 left_corner = 7 # inch top_corner = 0.8 image_height = 1.5 # inch left_location = np.arange(0, nCol * space_Col, space_Col) + left_corner top_location = np.arange(0, nRow * space_Row, space_Row) + top_corner left_location, top_location = np.meshgrid(left_location, top_location) left_location = np.concatenate(left_location) top_location = np.concatenate(top_location) # List Folders within the folder, one folder per slides listFolder = os.listdir(fig_mainDir) for iFolder in listFolder: fig_subDir = os.path.join(fig_mainDir, iFolder) #print(fig_subDir) slide = prs.slides.add_slide(blank_slide_layout) title = slide.shapes.title title.text = "Model - " + iFolder # List Figures within the folder listFigure = os.listdir(fig_subDir) for count, iFile in enumerate(listFigure): fig_fn = os.path.join(fig_subDir, iFile) #print(fig_fn) pic = slide.shapes.add_picture(fig_fn, Inches(left_location[count]), Inches(top_location[count]), height=Inches(image_height)) prs.save(pp_fnOutput)
def _test_template_usage(): template_to_be_tested = './linguappt/es/templates/vocab_spanish_classic.pptx' prs = Presentation(template_to_be_tested) templates = prs.slide_layouts # template idx:0 - name:Title and subtitle layout = templates.get_by_name("Title and subtitle") slide = prs.slides.add_slide(layout) holders = slide.shapes.placeholders title = holders[10] title.text_frame.text = 'Extra E1-1' subtitle = holders[11] subtitle.text_frame.text = '解析' # template idx:2 - name:Title 1 layout = templates.get_by_name("Title 1") slide = prs.slides.add_slide(layout) holders = slide.shapes.placeholders title = holders[10] title.text_frame.text = '名词' subtitle = holders[11] subtitle.text_frame.text = 'El nombre' note = slide.notes_slide note.notes_text_frame.text = "xxxxxxxxxxx" # template 2 slide = prs.slides.add_slide(templates[2]) holders = slide.shapes.placeholders word = holders[10] explaination = holders[11] word.text_frame.text = 'casa' explaination.text_frame.text = '家' # template 3 slide = prs.slides.add_slide(templates[3]) holders = slide.shapes.placeholders word = holders[10] explaination = holders[11] word.text_frame.text = 'niña' word.text_frame.paragraphs[0].font.color.rgb = RGBColor(0, 0, 255) explaination.text_frame.text = '小女孩' # template 4 slide = prs.slides.add_slide(templates[4]) holders = slide.shapes.placeholders for index in range(9): word = holders[10 + 2 * index] explaination = holders[11 + 2 * index] word.text_frame.text = str(index) explaination.text_frame.text = str(index) # template 5 slide = prs.slides.add_slide(templates[13]) holders = slide.shapes.placeholders for e in holders: print('%d %s' % (e.placeholder_format.idx, e.name)) for index in range(4): word = holders[10 + 2 * index] explaination = holders[11 + 2 * index] word.text_frame.text = str(index * 10) explaination.text_frame.text = str(index * 10) prs.save('test.pptx')
links = Nooznews["entries"][i]["link"] print(text) print(links) print(desc) News.append(text) #add headlines to News list Links.append(links) # add links to Links list # print (News) # print (Links) ### Create the Dictionary from the lists News and Links ### News_Dict = {} for i in range(len(News)): News_Dict[News[i]] = Links[i] print("") print(News_Dict) #test# ###### Create a Powerpoint ###### ### Loops over keys and values in the Dictionary and adds them to the slide ### ### Set up PPT ### prs = Presentation() for key, value in News_Dict.items(): this_slide = create_my_default_slide("%s" % key, " \n \n \n ") add_hyper_link(this_slide.shapes[1], value, value) print(len(prs.slides), ' slides δημιουργήθηκαν') ### save the Powerpoint ### prs.save('Whats_News.pptx') send_an_email()
height = Inches(7.5) fileName = remove(name.lower()) artistFileName = remove(artist_found.name.lower()) openFile = 'lyrics_' + artistFileName + '_' + fileName + '.txt' length_lyrics = length(list_lyrics) count = 0 num = 0 # make each slide and add the lyrics to the paragraph while num < length_lyrics: run = make_slide(prs) while 1: line = list_lyrics.pop(0) if (line == ''): break else: run.text += line + '\n' num += 1 # save powerpoint to directory chosen by user if pptx_name == '': print("Error, powerpoint name not found. Naming to Default") pptx_name = name + "_" + artist_found.name prs.save(file_location + '/' + pptx_name + '.pptx') print("") print("Presentation completed.") print("To find new songs, please change entries above.") print("Press X or the cancel button to exit") window.close
from pptx.util import Inches from parse import parse_csv, bonus_csv from slides import fill_slide, bonus_card presentation = Presentation() presentation.slide_width = Inches(2.5) presentation.slide_height = Inches(3.5) cards = parse_csv('cards.csv') bonus = bonus_csv('bonus.csv') def add_slide_from_card(c): layout = presentation.slide_layouts[6] slide = presentation.slides.add_slide(layout) fill_slide(slide, c) def add_bonus_card(c): layout = presentation.slide_layouts[6] slide = presentation.slides.add_slide(layout) bonus_card(slide, c) for card in cards: add_slide_from_card(card) for card in bonus: add_bonus_card(card) presentation.save('cards.pptx')
def builder(path, ref, fig_dict=dict(), var_dict=dict()): SCALE = 2 PAD = 0.3 from pptx import Presentation from pptx.util import Inches import tempfile import copy import os prs = Presentation(ref) out = Presentation() out.slide_width = prs.slide_width out.slide_height = prs.slide_height for slide in prs.slides: blank_slide_layout = out.slide_layouts[6] o_slide = out.slides.add_slide(blank_slide_layout) for shape in slide.shapes: try: if shape.text[0] == "!" and shape.text[ 1] == "(" and shape.text[-1] == ")": f = tempfile.NamedTemporaryFile(suffix=".png") fig = fig_dict[shape.text[2:-1]] if type(fig) == matplotlib.figure.Figure: fig.set_size_inches(SCALE * shape.width / Inches(1), SCALE * shape.height / Inches(1)) fig.set_tight_layout({"pad": PAD}) fig.savefig(f.name, format='png', dpi=300) pic = o_slide.shapes.add_picture(f.name, shape.left, shape.top, width=shape.width) continue elif type(fig) == plotly.graph_objs._figure.Figure: fig.write_image(f.name) pic = o_slide.shapes.add_picture(f.name, shape.left, shape.top, width=shape.width) continue fvar = False otxt = "" nvar = "" i = 0 while i < len(shape.text): if fvar: if shape.text[i] != "]": nvar += shape.text[i] else: otxt += var_dict[nvar] fvar = False nvar = "" elif shape.text[i] == "$" and shape.text[i + 1] == "[": fvar = True nvar = "" i += 1 else: otxt += shape.text[i] i += 1 shape.text = otxt cp = copy.deepcopy(shape.element) o_slide.shapes._spTree.insert_element_before(cp, 'p:extLst') continue except: pass try: img = shape.image.blob f = tempfile.NamedTemporaryFile() f.write(img) o_slide.shapes.add_picture(f.name, shape.left, shape.top, shape.width, shape.height) continue except: pass o_slide.shapes._spTree.insert_element_before( copy.deepcopy(shape.element), 'p:extLst') out.save(path)
if idx == 2: chart_data.add_series('Series 1', (lista[cnt][1][0], None)) if idx == 1: chart_data.add_series('Series 1', (lista[cnt][3][0], None)) chart.replace_data(chart_data) #print(chart.chart_type, idx) idx += 1 elif str(chart.chart_type).find("DOUGHNUT") != -1 and idx < 5: chart_data = ChartData() chart_data.categories = ["Chart"] if idx == 3: chart_data.add_series( None, (lista[cnt][2][0] / 100, lista[cnt][2][1] / 100)) if idx == 4: chart_data.add_series( None, (lista[cnt][4][0] / 100, lista[cnt][4][1] / 100, lista[cnt][4][2] / 100)) chart.replace_data(chart_data) #print(chart.chart_type, idx) #print(chart.chart_type) idx += 1 #print(idx) print(cnt) cnt += 1 if cnt >= len(lista) - 1: cnt = len(lista) - 1 #print("-------------") prs.save(path) print("DONE")
def audit_slide(content_dict : dict, doc_name : str, pptx_path : str) -> dict: audit_result_dict: dict = {'审核结果':[], '修改记录':[], '错误记录':[]} slide_sort_dict: dict = {'首页': [], '注意事项': [], '内容目录': [], '基线情况汇总':[]} # ----------------------- 首页 ----------------------- if '胰岛素规范临床实践' in content_dict[0]: # 获取首页页码 slide_sort_dict['首页'].append(0) temp_text: str = only_chinese(content_dict[0]) # 检查汇报人姓名 del_list: list = ['胰岛素规范临床实践', '总结', '报告', '汇报人'] for del_str in del_list: temp_text = temp_text.replace(del_str, '') if len(temp_text) > 0: if doc_name not in temp_text: audit_result_dict['错误记录'].append('【首页】汇报人姓名与上传报告医生姓名不一致!') else: audit_result_dict['错误记录'].append("【首页】第一页没有'胰岛素规范临床实践'文本!") # ----------------------- 内容目录 ----------------------- for i in [1,2]: if '注意事项' in content_dict[i]: # 获取注意事项与内容目录页码 slide_sort_dict['注意事项'].append(i) elif '治疗方案' in content_dict[i] or '病例分享' in content_dict[i]: slide_sort_dict['内容目录'].append(i) if slide_sort_dict['内容目录']: content_page_numb: int = slide_sort_dict['内容目录'][0] title_content_text: str = content_dict[content_page_numb] lack_title_list: list = [] title_list: list = ['患者情况汇总', '治疗方案', '治疗结果', '典型病例分享', '胰岛素规范实践的获益', '胰岛素规范实践临床展望'] for title_str in title_list: if not title_str in title_content_text: lack_title_list.append(title_str) if lack_title_list: lack_title_str: str = '、'.join(lack_title_list) audit_result_dict['错误记录'].append(f"【内容目录】缺少以下的模板中的字段:{lack_title_str}!") else: audit_result_dict['错误记录'].append('【内容目录】未发现内容目录页!') # ----------------------- 患者基线情况汇总 ----------------------- # 获取患者基线情况目录页码 for i in [2,3,4,5]: if '基线情况汇总' in content_dict[i]: slide_sort_dict['基线情况汇总'].append(i) # 生成基线情况汇总字符串 baseline_page_numbs: int = len(slide_sort_dict['基线情况汇总']) baseline_record: str = '' if baseline_page_numbs == 0 : audit_result_dict['错误记录'].append('【基线情况汇总】未发现标题含有-基线情况汇总-的页面!') else: for page_numb in slide_sort_dict['基线情况汇总']: baseline_record += content_dict[page_numb] # 检查基线情况汇总的填写正确与否 baseline_record_no_punctuation: str = re.sub(r'[^\w\s]', '', baseline_record) # result = re.findall(".*纳入(.*)名患者男性(.*)名女性(.*)名平均", s1) # for x in result: # print(x) # ----------------------- 注意事项 ----------------------- if slide_sort_dict['注意事项']: # 删除'注意事项'页面 audit_result_dict['修改记录'].append("【注意事项】删除了 注意事项 页面!") prs = Presentation(pptx_path) del_page_numb : int = slide_sort_dict['注意事项'][0] rId = prs.slides._sldIdLst[del_page_numb].rId prs.part.drop_rel(rId) del prs.slides._sldIdLst[del_page_numb] prs.save(pptx_path) return audit_result_dict
from pptx import Presentation from pptx.util import Inches prs = Presentation() title_only_slide_layout = prs.slide_layouts[5] slide = prs.slides.add_slide(title_only_slide_layout) shapes = slide.shapes shapes.title.text = 'Adding a Table' rows = cols = 2 left = top = Inches(2.0) width = Inches(6.0) height = Inches(0.8) table = shapes.add_table(rows, cols, left, top, width, height).table # set column widths table.columns[0].width = Inches(2.0) table.columns[1].width = Inches(4.0) # write column headings table.cell(0, 0).text = 'Foo' table.cell(0, 1).text = 'Bar' # write body cells table.cell(1, 0).text = 'Baz' table.cell(1, 1).text = 'Qux' prs.save('test_table.pptx')
def build_presentation(filename): prs = Presentation() slide_layout = prs.slide_layouts[6] # blank slide slide = prs.slides.add_slide(slide_layout) prs.save(filename) return
class OrgDraw: def __init__(self, workbookPaths, sheetName, draftMode): """ :type workbookPath: str :type sheetName: str """ self.presentation = Presentation('HDSPPTTemplate.pptx') self.presentation.slide_height = DrawChartSlide.MAX_HEIGHT_INCHES self.presentation.slide_width = DrawChartSlide.MAX_WIDTH_INCHES self.slideLayout = self.presentation.slide_layouts[8] self.multiOrgParser = MultiOrgParser(workbookPaths, sheetName) self.draftMode = draftMode def save(self, filename): self.presentation.save(filename) def _getDirects(self, aManager, location=None): """ :type aManager: str :return: """ peopleFilter = PeopleFilter() directReports = [] peopleFilter.addManagerFilter(aManager) peopleFilter.addIsTBHFilter(False) if location: peopleFilter.addLocationFilter(location) directReports.extend( self.multiOrgParser.getFilteredPeople(peopleFilter)) return directReports def drawAdmin(self): # Populate the manager list with managers who are entered in the spreadsheet so it's easier to match them # to the appropriate floor and identify them as 1 person even if they are entered in different ways in the # Manager column (Ben/Benjamin) managerSet = set( self.multiOrgParser.getFilteredPeople( PeopleFilter().addIsManagerFilter())) # Get all the entries in the manager column but remove entries that start with "_" as they are excluded intentionally allManagers = set([ SkeletonPerson(aManagerName) for aManagerName in self.multiOrgParser.getManagerSet() if (not aManagerName.startswith("_")) and "TBD" not in aManagerName ]) print "Info: Managers not entered as rows: {}".format( managerSet.difference(allManagers)) # Prefer Person type over SkeletonPerson type as it is more full featured - floors work better mergedManagerList = managerSet.union(allManagers) #pprint.pprint("Managers: {}".format(mergedManagerList)) managerEmployeeDict = {} for aManager in mergedManagerList: managerEmployeeDict[aManager] = self._getDirects(aManager) # A manager can have reports on more than one floor managersByFloor = {} for aManager in mergedManagerList: floors = aManager.getFloors() for floor in floors: if not floor in managersByFloor: managersByFloor[floor] = set() managersByFloor[floor].add(aManager) # Location: There can be people across locations reporting to the same manager: # Example: People report to Arno in Santa Clara and in Milan. # There will be a single slide for each unique location. Only direct reports in the specified location will be # drawn for aLocation in self.multiOrgParser.getLocationSet(): locationName = aLocation or self.multiOrgParser.getOrgName() # Floor: The floor (or other grouping) that separates manager. # Example: There are a lot of managers in Waltham so we break them up across floors # NOTE: All of the direct reports in the location will be drawn # Example: If Dave is on floor1 and floor2 in Waltham, then the same direct reports will be drawn both times sortedFloors = list(managersByFloor.keys()) sortedFloors.sort(cmp=self._sortByFloor) maxManagersPerSlide = 7 managersOnSlide = 0 partNum = 2 slideNameAddendum = "pt {}".format(partNum) for aFloor in sortedFloors: managerList = managersByFloor[aFloor] chartDrawer = DrawChartSlideAdmin( self.presentation, "{} Admin {}".format(locationName, aFloor), self.slideLayout) managerList = list(managerList) managerList.sort() for aManager in managerList: directReports = [] for aPerson in managerEmployeeDict[aManager][:]: if aPerson.getLocation() == aLocation: directReports.append(aPerson) #print "TODO: Removing - {}".format(aPerson) managerEmployeeDict[aManager].remove(aPerson) #print "TODO : Removed" #directReports.extend([aPerson for aPerson in managerEmployeeDict[aManager] if aPerson.getLocation() == aLocation]) # directReports.extend(self._getDirects(aManager, aLocation)) if not directReports: continue self.buildGroup(aManager.getPreferredName(), directReports, chartDrawer) managersOnSlide += 1 # Split the slide into multiple parts if it's getting too crowded if managersOnSlide >= maxManagersPerSlide: managersOnSlide = 0 chartDrawer.drawSlide() chartDrawer = DrawChartSlideAdmin( self.presentation, "{} Admin {}{}".format(locationName, aFloor, slideNameAddendum), self.slideLayout) partNum += 1 slideNameAddendum = "pt {}".format(partNum) # Keep track of whether this floor has any people so that we avoid spamming "WARNING" messages because # a slide is being drawn that's empty if managersOnSlide > 0: chartDrawer.drawSlide() managersOnSlide = 0 emptyManagerPeopleFilter = (PeopleFilter().addManagerEmptyFilter( ).addIsTBHFilter(False).addLocationFilter(locationName)) peopleMissingManager = (self.multiOrgParser.getFilteredPeople( emptyManagerPeopleFilter)) if peopleMissingManager: #Draw people who are missing a manager on their own slide chartDrawer = DrawChartSlideAdmin( self.presentation, "{} Missing Admin Manager".format(locationName), self.slideLayout) self.buildGroup("Chuck Norris", peopleMissingManager, chartDrawer) chartDrawer.drawSlide() def drawExpat(self): expats = self.multiOrgParser.getFilteredPeople( PeopleFilter().addIsExpatFilter()) #.addIsProductManagerFilter(False)) self._drawMiscGroups("ExPat", expats) def drawProductManger(self): productManagers = self.multiOrgParser.getFilteredPeople( PeopleFilter().addIsProductManagerFilter()) if not len(productManagers): return chartDrawer = DrawChartSlidePM(self.presentation, "Product Management", self.slideLayout) productBuckets = list( set([aPerson.getFeatureTeam() for aPerson in productManagers])) for aBucket in productBuckets: peopleList = [ aPerson for aPerson in productManagers if aPerson.getFeatureTeam() == aBucket ] # peopleList = sorted(peopleList, key=lambda x: x.getProduct(), cmp=self._sortByProduct) peopleList.sort() # Set default name for PM who don't have 'feature team' set # If default name isn't set, these people are accidentally filtered out in the # buildGroup function if not aBucket: aBucket = orgchart_parser.NOT_SET self.buildGroup(aBucket, peopleList, chartDrawer) # peopleProducts = list(set([aPerson.getProduct() for aPerson in productManagers])) # for aProduct in peopleProducts: # self.buildGroup(aProduct, [aPerson for aPerson in productManagers if aPerson.getProduct() == aProduct], chartDrawer) chartDrawer.drawSlide() def drawIntern(self): interns = self.multiOrgParser.getFilteredPeople( PeopleFilter().addIsInternFilter()) self._drawMiscGroups("Intern", interns) def _drawMiscGroups(self, slideName, peopleList): if not len(peopleList): return chartDrawer = DrawChartSlideExpatIntern(self.presentation, slideName, self.slideLayout) peopleFunctions = list( set([aPerson.getFunction() for aPerson in peopleList])) peopleFunctions.sort(cmp=self._sortByFunc) for aFunction in peopleFunctions: self.buildGroup(aFunction, [ aPerson for aPerson in peopleList if aPerson.getFunction() == aFunction ], chartDrawer) chartDrawer.drawSlide() def drawCrossFunc(self): crossFuncPeople = self.multiOrgParser.getCrossFuncPeople() if not len(crossFuncPeople): return chartDrawer = DrawChartSlide(self.presentation, "Cross Functional", self.slideLayout) functions = list( set([aPerson.getFunction() for aPerson in crossFuncPeople])) functions.sort(cmp=self._sortByFunc) for aFunction in functions: peopleFilter = PeopleFilter() peopleFilter.addFunctionFilter(aFunction) peopleFilter.addIsCrossFuncFilter() peopleFilter.addIsExpatFilter(False) peopleFilter.addIsInternFilter(False) funcPeople = self.multiOrgParser.getFilteredPeople(peopleFilter) self.buildGroup(aFunction, funcPeople, chartDrawer) chartDrawer.drawSlide() def drawAllProducts(self, drawFeatureTeams, drawLocations, drawExpatsInTeam): #Get all the products except the ones where a PM is the only member people = self.multiOrgParser.getFilteredPeople( PeopleFilter().addIsProductManagerFilter(False)) productList = list(set([aPerson.getProduct() for aPerson in people])) for aCrossFuncTeam in self.multiOrgParser.getCrossFuncTeams(): for aProductName in productList[:]: if aProductName.lower() == aCrossFuncTeam.lower(): productList.remove(aProductName) productList.sort(cmp=self._sortByProduct) for aProductName in productList: self.drawProduct(aProductName, drawFeatureTeams, drawLocations, drawExpatsInTeam) def drawProduct(self, productName, drawFeatureTeams=False, drawLocations=False, drawExpatsInTeam=True): """ :type productName: str """ if not productName: if not self.draftMode: return featureTeamList = [""] if drawFeatureTeams: featureTeamList = list( self.multiOrgParser.getFeatureTeamSet(productName)) functionList = list(self.multiOrgParser.getFunctionSet(productName)) functionList.sort(cmp=self._sortByFunc) teamModelText = None locations = [""] # If draw locations has been set (could still be an empty list) then break the chart up by locations. # if locations is set and isn't an empty list, only show the locations specified. if drawLocations is not None: locations = self.multiOrgParser.getLocationSet(productName) for drawLocation in drawLocations: if drawLocation not in locations: raise ValueError( "{} is not found in available locations: {}".format( drawLocations, locations)) for aLocation in drawLocations or locations: locationName = aLocation.strip() or self.multiOrgParser.getOrgName( ) for aFeatureTeam in featureTeamList: if not productName: slideTitle = orgchart_parser.NOT_SET elif drawFeatureTeams: teamName = "- {} ".format(aFeatureTeam) if not aFeatureTeam: if len(featureTeamList) > 1: teamName = "- Cross " else: teamName = "" slideTitle = "{} {}Feature Team".format( productName, teamName) else: slideTitle = "{}".format(productName) modelDict = self.multiOrgParser.getTeamModel() if productName in modelDict: teamModelText = modelDict[productName] chartDrawer = DrawChartSlide(self.presentation, slideTitle, self.slideLayout, teamModelText) if len(locations) > 1 and aLocation: chartDrawer.setLocation(locationName) for aFunction in functionList: if aFunction.lower( ) in self.multiOrgParser.getCrossFunctions(): continue peopleFilter = PeopleFilter() peopleFilter.addProductFilter(productName) peopleFilter.addFunctionFilter(aFunction) if drawLocations is not None: peopleFilter.addLocationFilter(aLocation) if drawFeatureTeams: peopleFilter.addFeatureTeamFilter(aFeatureTeam) else: if not drawExpatsInTeam: peopleFilter.addIsExpatFilter(False) peopleFilter.addIsInternFilter(False) # peopleFilter.addIsProductManagerFilter(False) functionPeople = self.multiOrgParser.getFilteredPeople( peopleFilter) self.buildGroup(aFunction, functionPeople, chartDrawer) chartDrawer.drawSlide() def drawTBH(self): totalTBHSet = set( self.multiOrgParser.getFilteredPeople( PeopleFilter().addIsTBHFilter())) tbhLocations = set([aTBH.getLocation() for aTBH in totalTBHSet]) or [""] tbhProducts = list(set([aTBH.getProduct() for aTBH in totalTBHSet])) or [""] tbhProducts.sort(cmp=self._sortByProduct) tbhFunctions = list(set([aTBH.getFunction() for aTBH in totalTBHSet])) tbhFunctions.sort(cmp=self._sortByFunc) for aLocation in tbhLocations: title = "Hiring" # Location might not be set. if aLocation: title = "{} - {}".format(title, aLocation) chartDrawer = DrawChartSlideTBH(self.presentation, title, self.slideLayout) for aFunction in tbhFunctions: productTBHList = self.multiOrgParser.getFilteredPeople( PeopleFilter().addIsTBHFilter().addFunctionFilter( aFunction).addLocationFilter(aLocation)) productTBHList = sorted(productTBHList, self._sortByFunc, lambda tbh: tbh.getProduct()) self.buildGroup(aFunction, productTBHList, chartDrawer) chartDrawer.drawSlide() # for aProduct in tbhProducts: # productTBHList = self.orgParser.getFilteredPeople(PeopleFilter().addIsTBHFilter().addProductFilter(aProduct).addLocationFilter(aLocation)) # productTBHList = sorted(productTBHList, self._sortByFunc, lambda tbh: tbh.getProduct()) # self.buildGroup(aProduct, productTBHList, chartDrawer) # # chartDrawer.drawSlide() def _sortByFunc(self, a, b): funcOrder = [ "lead", "leadership", "head coach", "product management", "product manager", "pm", "po", "product owner", "product owner/qa", "technology", "ta", "technology architect", "tech", "sw architecture", "dev", "development", "development (connectors)", "qa", "quality assurance", "stress", "characterization", "auto", "aut", "automation", "sustaining", "solutions and sustaining", "ui", "ux", "ui/ux", "user experience", "inf", "infrastructure", "devops", "cross functional", "cross", "doc", "documentation" ] if a.lower() in funcOrder: if b.lower() in funcOrder: if funcOrder.index(a.lower()) > funcOrder.index(b.lower()): return 1 return -1 if b.lower() in funcOrder: return 1 return 0 def _sortByFloor(self, a, b): floorOrder = self.multiOrgParser.getFloorSortOrder() if a.lower() in floorOrder: if b.lower() in floorOrder: if floorOrder.index(a.lower()) > floorOrder.index(b.lower()): return 1 return -1 if b.lower() in floorOrder: return 1 return 0 def _sortByProduct(self, a, b): productOrder = self.multiOrgParser.getProductSortOrder() if a.lower() in productOrder: if b.lower() in productOrder: if productOrder.index(a.lower()) > productOrder.index( b.lower()): return 1 return -1 if b.lower() in productOrder: return 1 return 0 def buildGroup(self, functionName, functionPeople, chartDrawer): """ :type functionName: str :type functionPeople: list :type chartDrawer: ppt_draw.DrawChartSlide :return: """ functionPeople = [ person for person in functionPeople if person.getRawName().strip() != "" ] if len(functionPeople) == 0: return if not functionName: if not self.draftMode: return functionName = orgchart_parser.NOT_SET chartDrawer.addGroup(functionName, functionPeople)
url = "https://script.google.com/macros/s/" url += api_key url += "/exec?text=" + str_in url += "&source=" + source url += "&target=" + target rr = requests.get(url) return rr.text if __name__ == '__main__': path_to_presentation = "test.pptx" prs = Presentation(path_to_presentation) print("start") for ns, slide in enumerate(prs.slides): for nsh, shape in enumerate(slide.shapes): if not shape.has_text_frame: continue for np, paragraph in enumerate(shape.text_frame.paragraphs): for rs, run in enumerate(paragraph.runs): str_in = run.text str_out = translate(str_in) prs.slides[ns].shapes[nsh].text_frame.paragraphs[np].runs[rs].text = str_out sleep(1.5) print(np) prs.save('test_trans.pptx') print("end")
# https://towardsdatascience.com/creating-presentations-with-python-3f5737824f61 from __future__ import print_function from pptx import Presentation from pptx.util import Cm, Pt figname1 = "fig/albert.jpg" figname2 = "fig/curie.jpg" prs = Presentation() print(prs) print("prs.slide_width = %7r em = %5.2f cm" % (prs.slide_width, prs.slide_width.cm)) print("prs.slide_height = %7r em = %5.2f cm" % (prs.slide_height, prs.slide_height.cm)) # PAGE 1 lyt = prs.slide_layouts[0] # choosing a slide layout slide1 = prs.slides.add_slide(lyt) # adding a slide title = slide1.shapes.title # assigning a title subtitle = slide1.placeholders[1] # placeholder for subtitle title.text = "Hey, This is a Slide! How exciting!" # title subtitle.text = "Really?" # subtitle # PAGE 2 slide2 = prs.slides.add_slide(prs.slide_layouts[6]) fig1 = slide2.shapes.add_picture(figname1, Cm(3.), Cm(3.), height=Cm(11.)) #,width=Cm(10.)) fig2 = slide2.shapes.add_picture(figname2, Cm(12.), Cm(3.), height=Cm(11.)) #,width=Cm(10.)) prs.save("placefig.pptx") # saving file
cnt = 0 os.mkdir('output') file_list = os.listdir('convert') for file in file_list: os.mkdir('temp') convert_from_path('convert/' + file, output_folder='temp', fmt='JPG') img_list = os.listdir('temp') for i in range(0, len(img_list)): os.rename('temp/' + img_list[i], 'temp/' + str(i) + ".jpg") prs = Presentation('template.pptx') cover_path = '0.jpg' slide = prs.slides[0] pic = slide.shapes.add_picture(cover_path, 0, 0) SLD_LAYOUT_TITLE_AND_CONTENT = 6 img_list = os.listdir('temp') for i in range(0, len(img_list)): slide_layout = prs.slide_layouts[SLD_LAYOUT_TITLE_AND_CONTENT] slide = prs.slides.add_slide(slide_layout) img_path = 'temp/' + str(i) + '.jpg' pic = slide.shapes.add_picture(img_path, 0, 0) cnt = cnt + 1 rId = prs.slides._sldIdLst[1].rId prs.part.drop_rel(rId) del prs.slides._sldIdLst[1] prs.save('output/' + file + '.pptx') for img in img_list: os.remove('temp/' + img) os.rmdir('temp') print(cnt)
from pptx.enum.chart import XL_LABEL_POSITION from pptx.util import Pt from pptx.enum.chart import XL_LEGEND_POSITION # create presentation with 1 slide ------ prs = Presentation() slide = prs.slides.add_slide(prs.slide_layouts[5]) # define chart data --------------------- chart_data = ChartData() chart_data.categories = ['West', 'East', 'North', 'South', 'Other'] chart_data.add_series('Series 1', (0.135, 0.324, 0.180, 0.235, 0.126)) # add chart to slide -------------------- x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5) chart = slide.shapes.add_chart( XL_CHART_TYPE.PIE, x, y, cx, cy, chart_data ).chart # define axis and labels -------------- chart.has_legend = True chart.legend.position = XL_LEGEND_POSITION.BOTTOM chart.legend.include_in_layout = False chart.plots[0].has_data_labels = True data_labels = chart.plots[0].data_labels data_labels.number_format = '0%' data_labels.position = XL_LABEL_POSITION.OUTSIDE_END prs.save('pieChart.pptx')
shapes = slide.shapes shapes.title.text = 'Adding Shapes' shape1 = shapes.add_shape(MSO_SHAPE.RECTANGULAR_CALLOUT, Inches(3.5), Inches(2), Inches(2), Inches(2)) shape1.fill.solid() shape1.fill.fore_color.rgb = RGBColor(0x1E, 0x90, 0xFF) shape1.fill.fore_color.brightness = 0.4 shape1.text = 'See! There is home!' shape2 = shapes.add_shape(MSO_SHAPE.ACTION_BUTTON_HOME, Inches(3.5), Inches(5), Inches(2), Inches(2)) shape2.text = 'Home' prs.save('shapes.pptx') #Add table to slides from pptx import Presentation from pptx.util import Inches prs = Presentation() title_only_slide_layout = prs.slide_layouts[5] slide = prs.slides.add_slide(title_only_slide_layout) shapes = slide.shapes shapes.title.text = 'Students Data' rows = 4 cols = 3 left = top = Inches(2.0)
# Creating slide layout first_slide_layout = presentation.slide_layouts[6] """ Ref for slide types: 0 -> title and subtitle 1 -> title and content 2 -> section header 3 -> two content 4 -> Comparison 5 -> Title only 6 -> Blank 7 -> Content with caption 8 -> Pic with caption """ left = top = Cm(0) width = presentation.slide_width height = presentation.slide_height for img_path in sorted( Path(r'./').glob('frame_*.jpg'), key=lambda path: float(path.stem.rsplit("_", 1)[1])): slide = presentation.slides.add_slide(first_slide_layout) pic = slide.shapes.add_picture(str(img_path), left, top, width=width, height=height) presentation.save("story.pptx")
def generate_report(round_list=[], path0=[], options=[1, 1, 1, 1, 1, 1]): ''' generate the comparison report for the given json files input parameters: round_list: the list of json files names; path0: the path that contains the json files. if round_list gives the full path, path0 is not required ''' if len(round_list) == 0: if len(path0) == 0: print( 'ERROR! You must enter either the file list or the folder/path contains the files!' ) else: round_list = [f for f in listdir(path0) if isfile(join(path0, f))] ## start to create slides prs = Presentation('Workload.pptx') slide_width = 9.0 slide_height = 6.5 ## create a title page title_slide_layout = prs.slide_layouts[0] slide = prs.slides.add_slide(title_slide_layout) title = slide.shapes.title title.text = 'RADOS Test Result Comparison' subtitle = slide.placeholders[13] subtitle.text = "{:%m-%d-%Y}".format(date.today()) subtitle = slide.placeholders[10] subtitle.text = "Generated by PBJ Parser and Analyzer \nWDLABS" ## create an outline page for all settings out_slide_layout = prs.slide_layouts[4] # Create the summary graph out_slide = prs.slides.add_slide(out_slide_layout) title = out_slide.shapes.title title.text = "Outline" subtitle = out_slide.placeholders[11] subtitle.text = "PBJ Rados Benchmark Settings" sub_lines = 0 pbjtr = pbj.PbjTestReport(path0 + round_list[0]) test_list = pbjtr.tests.keys() round_num = len(round_list) test_num = len(test_list) if test_num >= 5: sub_lines = 2 new_list = all_items_in_one_line(test_list) new_list = [new_list] elif test_num >= 3: sub_lines = sub_lines + test_num / 2 new_list = two_items_per_line(test_list) else: sub_lines = sub_lines + test_num new_list = test_list if round_num > 20: sub_lines = 10 new_list2 = all_items_in_one_line(round_list, options=1) new_list2 = [new_list2] elif round_num > 10: sub_lines = sub_lines + round_num / 2 new_list2 = two_items_per_line(round_list) else: sub_lines = sub_lines + round_num new_list2 = round_list font_size = item_font_size(sub_lines) subtitle = out_slide.placeholders[10] tf = subtitle.text_frame tf.text = '' add_items_to_tf(out_slide, 'Benchmark test(s):' + str(test_num), new_list, font_size) add_items_to_tf(out_slide, 'Benchmark round(s):' + str(round_num), new_list2, font_size) # create a notation page out_slide_layout = prs.slide_layouts[4] # Create the summary graph out_slide = prs.slides.add_slide(out_slide_layout) title = out_slide.shapes.title title.text = "Notations" subtitle = out_slide.placeholders[11] subtitle.text = "PBJ Rados Benchmark Result Summary" subtitle = out_slide.placeholders[10] tf = subtitle.text_frame tf.text = '' font_size = 16 str_list = [ 'normal: the number of rounds that the values satisfy normal distribution', 'non-normal: the number of rounds that the values do not satisfy normal distribution', 'invalid: the collected dataset is too small for a valid hypothesis test', 'F-value /p-value: F value/p-value returned from 2-sided F-test', 'F-result: if p-value is less than 0.05, the hypothesis of same mean of normal distribution is rejected (0); if it is greater, then the hypothesis is not rejected (1). Otherwise, no enough data for F-test (-1)', 'H-value/p-value: H value/p-value returned from one-way H-test', 'H-result: if p-value is less than 0.05, the hypothesis of same median is rejected (0); if it is greater, then the hypothesis is not rejected (1). Otherwise, no enough data for H-test (-1)' ] add_items_to_tf(out_slide, 'Consistency summary for all rounds', str_list, font_size) str_list = [ '1: likely normal distribution', '0: unlikely normal distribution', '-1: no enough data for test' ] add_items_to_tf(out_slide, 'Normality summary for all rounds', str_list, font_size) # create a notation page out_slide_layout = prs.slide_layouts[4] # Create the summary graph out_slide = prs.slides.add_slide(out_slide_layout) title = out_slide.shapes.title title.text = "Notations" subtitle = out_slide.placeholders[11] subtitle.text = "PBJ Rados Benchmark Result Summary" subtitle = out_slide.placeholders[10] tf = subtitle.text_frame tf.text = '' font_size = 16 str_list = [ 'One to one comparison with 4 notations; the order of rounds is listed before', '1: two samples likely have the same mean', '0: two sample unlikely have no same mean', '-1: at least one vector has no enough data', '-2: at least one vector is not normal distribution' ] add_items_to_tf( out_slide, 'Summary for pairs (one-way ANOVA for normal distribution)', str_list, font_size) str_list = [ 'One to one comparison with 3 notations; the order of rounds is listed before', '1: two samples likely from the same distribution', '0: two samples unlikely from the same distribution', '-1: at least one sample has no enough data' ] add_items_to_tf( out_slide, 'Summary for pairs (two-sample KS test for continuous distribution)', str_list, font_size) str_list = [ 'One to one comparison with 3 notations; the order of rounds is listed before', '1: two samples likely have the same mean', '0: two samples unlikely have the same mean', '-1: at least one sample has no enough data' ] add_items_to_tf( out_slide, 'Summary for pairs (two-sample T-test for identical mean)', str_list, font_size) ## add the individual slides metric_str = ['radosBench', 'radosBench_BW', 'Throughput (MBPS)'] raw_data = add_metric_to_slide(prs, round_list, path0, metric_str, options, gen_sum=0, reduced_num=0, method_v=0) metric_str = ['radosBench', 'radosBench_LAT', 'Latency (second)'] raw_data = add_metric_to_slide(prs, round_list, path0, metric_str, options, gen_sum=0, reduced_num=0, method_v=1) prs.save('rados_compare2.pptx') return raw_data ########### main test#################### #round_list=['pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-10_170401033958.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-11_170401035608.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-12_170401041212.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-13_170401042817.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-14_170401044420.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-15_170401050021.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-16_170401051627.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-17_170401053227.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-18_170401054832.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-19_170401060433.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-1_170401011547.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-20_170401062038.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-21_170403095513.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-22_170403101127.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-23_170403102730.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-24_170403104330.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-25_170403105933.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-26_170403111530.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-27_170403113127.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-28_170403114732.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-29_170403120339.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-2_170401013150.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-30_170403121938.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-3_170401014747.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-4_170401020352.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-5_170401021952.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-6_170401023557.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-7_170401025200.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-8_170401030801.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-9_170401032402.json' ] #round_list=['pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-10_170401033958.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-11_170401035608.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-12_170401041212.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-14_170401044420.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-15_170401050021.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-16_170401051627.json', # 'pbj_IWasp_BS_XeonE_11_OSDs_30G,10G_+_MVA72_1_OSD_10G,10G_2x.6Ghz_2G_MR-13_170401042817.json'] # #path0='./json/' #options=[0,0,0,0,0,1] # #generate_report(round_list,'./json/',[1,1,1,1,1,1]) #generate_report([],'./json2/',[1,1,1,1,1,1]) #generate_report([],'./json2/')
def open_file(filename, target): if '.txt' in filename: file_Object = open(filename, 'r') string_Holder = file_Object.readlines() file_Object.close() file_Object = open(filename, 'w') for x in string_Holder: if target in x: y = x.replace(target, '*' + target + '*') file_Object.write(y) else: file_Object.write(x) if '.docx' in filename: doc = Document(filename) for paragraph in doc.paragraphs: if target in paragraph.text: for run in paragraph.runs: if target in run.text: if run.text == target: run.font.highlight_color = WD_COLOR_INDEX.YELLOW continue x = run.text.split(target) run.clear() run.add_text(x[0]) temp = paragraph.add_run("", run.style) temp.add_text(target) temp.font.highlight_color = WD_COLOR_INDEX.YELLOW temp2 = paragraph.add_run(x[1], run.style) doc.save(filename) if '.pptx' in filename: prs = Presentation(filename) text_runs = [] for slides in prs.slides: for shape in slides.shapes: if not shape.has_text_frame: continue text_frame = shape.text_frame for paragraph in text_frame.paragraphs: for run in paragraph.runs: if target in run.text: if run.text == target: run.font.fill.solid() d = RGBColor(0xff, 0xff, 0x00) run.font.fill.fore_color.rgb = d continue x = run.text.split(target) run.text = x[0] temp = paragraph.add_run() temp.text = target temp.font.bold = run.font.bold temp.font.italic = run.font.italic temp.font.language_id = run.font.language_id temp.font.name = run.font.name temp.font.size = run.font.size temp.font.underline = temp.font.underline temp.font.fill.solid() d = RGBColor(0xff, 0xff, 0x00) temp.font.fill.fore_color.rgb = d temp2 = paragraph.add_run() temp2.font.bold = run.font.bold temp2.font.italic = run.font.italic temp2.font.language_id = run.font.language_id temp2.font.name = run.font.name temp2.font.size = run.font.size temp2.font.underline = temp.font.underline temp2.text = x[1] prs.save(filename) if '.xlsx' in filename: wb = load_workbook(filename) yellowFill = PatternFill(start_color='FFFFFF00', end_color='FFFFFF00', fill_type='solid') for ws in wb.worksheets: for row in ws.iter_rows(): for cell in row: if cell.value == None: continue if type(cell.value) != str: temp = str(cell.value) if target in temp: cell.fill = yellowFill continue if target in cell.value: cell.fill = yellowFill wb.save(filename) os.startfile(filename)
def make_avgSnr(): # datenow = str(date.today())[2:4] + str(date.today())[5:7] + str( date.today())[8:10] name = 'tester' filename = 'createCSV/' + datenow + 'test.csv' excelname = 'Excel/' + datenow + 'test' + name + '.xlsx' picturename = 'chartPicture/avgSnrChart_' pptname = 'ppt/' + datenow + 'test' + name + '.pptx' titletext = 'title' f = open(filename, 'r') station_key = dict() station_col = 2 # 초기 기지국 별 셀 위치 xbar_row = 2 # 초기 x축 셀 위치 cnt_col = 2 # 초기 개수 셀 위치 cnt_row = 2 # 초기 개수 셀 위치 count = [] # # excel 객체 생성 wb = openpyxl.Workbook() # create Sheet ws = wb.active ws.title = 'first' # pptx 객체 생성 // 파일을 열려면 인자로 경로 와 파일명 넣어줌. prs = Presentation() title_slide_layout = prs.slide_layouts[0] slide = prs.slides.add_slide(title_slide_layout) title = slide.shapes.title subtitle = slide.placeholders[1] title.text = "title" subtitle.text = "subtitle" slide_layout = prs.slide_layouts[1] slide = prs.slides.add_slide(slide_layout) slide_title_shape = slide.shapes.title slide_title_shape.text = "STATION LIST(" + titletext + ")" slide_body_shape = slide.placeholders[1] # text box 객체 slide_body_tf = slide_body_shape.text_frame check_pptx = os.path.exists(pptname) if check_pptx == True: os.unlink(pptname) # create empty excel check_file = os.path.exists(excelname) if check_file == True: os.unlink(excelname) wb.save(excelname) else: wb.save(excelname) # load empty excel write_wb = openpyxl.load_workbook(excelname) write_ws = write_wb.active for line in f: rawdata = json.loads(line.replace("'", "\"")) if rawdata['payload']['station'] in station_key: if rawdata['payload']['avgSnr'] != 'null': station_key[rawdata['payload']['station']].append( float(rawdata['payload']['avgSnr'])) else: if rawdata['payload']['avgSnr'] != 'null': station_key[rawdata['payload']['station']] = [ float(rawdata['payload']['avgSnr']) ] write_ws.cell(row=1, column=1, value='x축범위') for items in station_key.items(): avg = round(sum(items[1]) / len(items[1]), 2) ys, xs, patches = plt.hist(items[1], range=(0, 40), color='r', edgecolor='black', linewidth=1.2, rwidth=0.8, bins=40, alpha=0.4) count.append(ys) write_ws.cell(row=1, column=station_col, value='avgSnr(station : ' + items[0] + ')') station_col = station_col + 1 plt.xlabel('avgSnr') plt.ylabel('개수') plt.title('avgSnr 차트\n(station : ' + items[0] + ') 평균 : ' + str(avg)) plt.grid() plt.axvline(avg, linestyle='--') plt.minorticks_on() check_picture = os.path.exists(picturename + items[0] + '.png') if check_picture == True: #delete picture os.unlink(picturename + items[0] + '.png') # save picture plt.savefig(picturename + items[0] + '.png', dpi=500) else: # save picture plt.savefig(picturename + items[0] + '.png', dpi=500) # show chart # plt.show() plt.clf() # initialize # save pptx slide_p = slide_body_tf.add_paragraph() slide_p.text = items[0] slide_p.font.size = Pt(17) slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(slide_layout) slide.shapes.add_picture(picturename + items[0] + '.png', Inches(0.5), Inches(0.5), width=Inches(9), height=Inches(6)) prs.save(pptname) # insert excel for i in range(0, len(xs) - 1): write_ws.cell(row=xbar_row, column=1, value=xs[i]) # x축 범위 xbar_row = xbar_row + 1 for i in range(len(count)): for j in range(len(count[i])): write_ws.cell(row=cnt_row, column=cnt_col, value=int(count[i][j])) cnt_row = cnt_row + 1 if cnt_row == 42: cnt_row = 2 cnt_col = cnt_col + 1 # save excel write_wb.save(excelname)