예제 #1
0
파일: makePPT.py 프로젝트: jcc-ne/PyDesk
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)
예제 #2
0
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')
예제 #3
0
파일: svg.py 프로젝트: shapiromatron/hawc
    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
예제 #4
0
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
예제 #5
0
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)
예제 #6
0
파일: slider.py 프로젝트: ernaxe/sliderobot
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)
예제 #7
0
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)
예제 #8
0
파일: figures.py 프로젝트: jcc-ne/PyDesk
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')
예제 #9
0
파일: gen_ppt.py 프로젝트: castisdev/d7
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
예제 #10
0
	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')
예제 #11
0
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)
예제 #12
0
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)
예제 #13
0
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)
예제 #16
0
 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
예제 #17
0
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
예제 #18
0
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')
예제 #19
0
    def _write_details(self, filepath):
        self.ppt = Presentation()
        for channel in self.channels:
            self.write_slide(channel)

        # Save the file
        self.ppt.save(filepath)
예제 #20
0
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
예제 #22
0
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 __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)
예제 #24
0
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)
예제 #26
0
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')
예제 #27
0
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)
예제 #28
0
	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
예제 #29
0
    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()
예제 #30
0
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")
import os
from pptx import Presentation

#  創立投影片物件
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 = "Hello, World!"
subtitle.text = "python-pptx was here!"

# 儲存 PPT
prs.save(os.getcwd() + '/hello_world.pptx')
예제 #32
0
def given_slide_placeholder_with_no_direct_pos_or_size_settings(context):
    prs = Presentation(test_pptx('ph-inherit-props'))
    context.placeholder = prs.slides[0].placeholders[0]
예제 #33
0
def given_a_SlideShapes_obj_having_type_shape_at_off_idx(context, type, idx):
    prs = Presentation(test_pptx('shp-shape-access'))
    context.shapes = prs.slides[1].shapes
"""

##Import modules and set up
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
import random
import os.path


class color:
    BOLD = '\033[1m'
    END = '\033[0m'


##Update this section ONLY each time
prs = Presentation(
    r'file location and presentation name')  #must fill out at start
image_folder = r'file locaton for images to be saved'  #must fill out at start
pres_name = 'presentation name'
get_photos = 'y'  #write 'y' if you want to save all the photos in a folder otherwise write 'n'
scan_text = 'y'  #write 'y' if you want to scan the text for a phrase otherwise write 'n'
searchText = 'Write Text Here'

##Read the text
if scan_text.lower() == 'y':  #forcing lower case just in case
    textContent = []

    for slide in prs.slides:
        for shape in slide.shapes:
            if not shape.has_text_frame:
                continue
            for paragraph in shape.text_frame.paragraphs:
def permit_double(select):
    # csv読み込み版
    layout_load = pd.read_csv('./samples/layout.csv',
                              encoding='cp932',
                              header=0)
    # ldata:id(インデックス)、残り全部itemに入ってる
    # 最初に両方に値が入っているパターンを想定
    # 入っていない場合は入っている方を問題タイトルに、入っている場合は先に出てきたほうをタイトル、あとの方をタイトルのラベルにする
    l_titlelabel = []
    for ldata, item in layout_load.iterrows():
        if ('Q{}'.format(select) in item[1]) == True:
            if item[4] and item[5]:
                l_title = item[4]
                l_titlelabel.insert(len(l_titlelabel), item[5])
            else:
                if math.isnan(item[4]):
                    l_title = item[5]
                else:
                    l_title = item[4]

    # rawdataから問題の回答を取得する
    raw_load = pd.read_csv('./samples/rawdata.csv',
                           header=None,
                           encoding='shift_jisx0213')

    # rawdataの一列目から関連するインデックスを取得する
    # Q11に関連する部分を割り出す
    # 各idごとに最後の値(掲載許可)を取得
    rels = []
    ans = []
    # python3.7以降では仕様化されたはずのlistの順番が入れ替わるのでOrderedDict()で固定にする
    permits = OrderedDict()
    rcount = 0
    for rdata, vals in raw_load.iterrows():
        if rcount == 0:
            for rrans in vals:
                if ('Q{}'.format(select) in rrans) == True:
                    rels.append(1)
                else:
                    rels.append(0)
        else:
            ans.append(vals)
            try:
                if math.isnan(vals[len(vals) - 1]):
                    permits[vals[0]] = '0'
            except:
                permits[vals[0]] = '1'
        rcount += 1

    # リストrelsにより関連する行のあぶり出しができたのでこのインデックス数を取得する
    index_num = [n for n, v in enumerate(rels) if v == 1]

    # index_numを当てはめた引数変数を取得し、Q8の回答のみのリストを作成する
    # 今回は記述回答データが2枠あるので、忘れずに2枠分取得する
    this_ans_one = []
    this_ans_two = []
    this_ids = []
    ids_count = 1
    for this in ans:
        this_ans_one.append(this[index_num[0]])
        this_ans_two.append(this[index_num[1]])
        this_ids.append(ids_count)
        ids_count += 1

    # jinja2テンプレート出力
    env = Environment(loader=FileSystemLoader('./', encoding='utf8'))
    tmpl = env.get_template(
        'jinja2_templetes/templetes_extra_nostalgicspeed_two.tmpl')
    # 商品情報を入れるリストを宣言、初期化
    items = []
    per_count = 0
    # ループでitemsにIDとテキストをappendする
    # 必要:id、掲載許可、値2枠分
    permit = [int(per_val) for per_val in dict(permits).values()]
    for ids, perms, val_one, val_two in zip(this_ids, permit, this_ans_one,
                                            this_ans_two):
        items.append({
            'ID': ids,
            'PERMIT': perms,
            'ANS_ONE': val_one,
            'ANS_TWO': val_two
        })

    # #ここでtmplの変数に入る文字を指定している
    html = tmpl.render({
        'title': l_title,
        'sub_label': l_titlelabel,
        'item': items
    })
    with open('jinja2_templetes/Qextra_nostalgicspeed_two.html',
              mode='w') as f:
        f.write(str(html))

    # seleniumでブラウザ表示(動作問題なし)
    options = Options()
    options.add_argument('--headless')
    driver = webdriver.Chrome(options=options)
    driver.get(
        'file:///Users/t_sasaki/Documents/%E6%A5%AD%E5%8B%99/%E3%82%A2%E3%83%B3%E3%82%B1%E3%83%BC%E3%83%88/%E3%82%AB%E3%83%9F%E3%82%AA%E3%83%B3/macro_mk/jinja2_templetes/Qextra_nostalgicspeed_two.html'
    )
    page_width = driver.execute_script('return document.body.scrollWidth')
    page_height = driver.execute_script('return document.body.scrollHeight')
    driver.set_window_size(page_width, page_height)
    driver.save_screenshot('save_images/Q{}.png'.format(select))
    driver.quit()

    # PPを開いて画像を張り込む
    # 作成した画像をPPに貼り付ける
    # PPの呼び出し
    prs = Presentation('./static/pp/template.pptx')
    # 画像を中央配置にするためにスライドの幅と高さを取得する
    width = prs.slide_width
    height = prs.slide_height
    # 貼り付ける画像の読み込み
    fnms = ['./save_images/Q{}.png'.format(select)]
    # ファイルでループさせる
    for fnm in fnms:
        # スライドの追加。6は白紙のスライド
        add_s = prs.slide_layouts[6]
        # 合体?
        slide = prs.slides.add_slide(add_s)
        # 画像の挿入
        pic = slide.shapes.add_picture(fnm, 0, 0, width=None, height=None)
        # 画像を中心に設置
        pic.left = int((width - pic.width) / 4)
        pic.top = int((height - pic.height) / 4)
    # とりあえず画像サイズについては個々人で調整してもらう方向で
    prs.save('./static/pp/template.pptx')
예제 #36
0
from pptx import Presentation

prs = Presentation()

# Create title slide
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 = "A Presentation Made via Python"
subtitle.text = "Fadjar Fathurrahman"

# layout
slide = prs.slides.add_slide(prs.slide_layouts[1])

shapes = slide.shapes
title_shape = shapes.title
body_shape = shapes.placeholders[1]

title_shape.text = "Test adding a bullet slide"
tf = body_shape.text_frame
tf.text = "First item"

prs.save("01_hello.pptx")
예제 #37
0
def given_a_GradientStop_object_as_stop(context):
    shape = Presentation(test_pptx("dml-fill")).slides[0].shapes[4]
    context.stop = shape.fill.gradient_stops[0]
예제 #38
0
def given_a_group_shape(context):
    prs = Presentation(test_pptx('shp-common-props'))
    sld = prs.slides[0]
    context.shape = sld.shapes[3]
예제 #39
0
def given_a_FreeformBuilder_object_as_builder(context):
    shapes = Presentation(test_pptx('shp-freeform')).slides[0].shapes
    builder = shapes.build_freeform()
    context.builder = builder
예제 #40
0
def given_a_connector_having_its_end_point_at_x_y(context, x, y):
    prs = Presentation(test_pptx('shp-connector-props'))
    sld = prs.slides[0]
    context.connector = sld.shapes[0]
예제 #41
0
def given_a_graphic_frame_containing_a_table(context):
    prs = Presentation(test_pptx('shp-access-chart'))
    sld = prs.slides[1]
    context.shape = sld.shapes[0]
예제 #42
0
def then_text_box_appears_in_slide(context):
    prs = Presentation(saved_pptx_path)
    textbox = prs.slides[0].shapes[0]
    textbox_text = textbox.text_frame.paragraphs[0].runs[0].text
    assert textbox_text == test_text
예제 #43
0
def given_a_connector_and_a_1_inch_square_picture_at_0_0(context):
    prs = Presentation(test_pptx('shp-connector-props'))
    shapes = prs.slides[1].shapes
    context.picture = shapes[0]
    context.connector = shapes[1]
예제 #44
0
def given_a_SlideShapes_object_containing_6_shapes(context):
    prs = Presentation(test_pptx('shp-shape-access'))
    context.shapes = prs.slides[0].shapes
예제 #45
0
#!/usr/bin/env python

from pptx import Presentation

prs = Presentation()

# 1st slide
title_slide_layouts = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layouts)

title = slide.shapes.title
subtitle = slide.placeholders[1]

title.text = "Hello World!"
subtitle.text = "python-pptx was here!"

# 2nd slide
bullet_slide_layouts = prs.slide_layouts[1]
slide = prs.slides.add_slide(bullet_slide_layouts)
shapes = slide.shapes

title_shape = shapes.title
body_shape = shapes.placeholders[1]

title_shape.text = "Adding a bullet slide "

tf = body_shape.text_frame
tf.text = "Find the bullet slide layout"

p = tf.add_paragraph()
p.text = 'Use _TextFrame.text for first bullet'
예제 #46
0
def given_a_movie_shape(context):
    prs = Presentation(test_pptx('shp-movie-props'))
    context.movie = prs.slides[0].shapes[0]
예제 #47
0
#################################
table_fname = os.path.join("/Temp/stock_report",
                           '{company}_table.png'.format(company=company))
plt.savefig(table_fname)

# Step3) 보고서 작성하기
import datetime
from pptx import Presentation  # 라이브러리
from pptx.util import Inches  # 사진, 표등을 그리기 위해
import os

#################################
## 파워포인트 객체 선언
#################################
today = datetime.datetime.today().strftime('%Y%m%d')
prs = Presentation()  # 파워포인트 객체 선언

#################################
## 제목 장표 추가
#################################
title_slide_layout = prs.slide_layouts[0]  # 0 : 제목슬라이드에 해당
slide = prs.slides.add_slide(title_slide_layout)  # 제목 슬라이드를 파워포인트 객체에 추가

# 제목 - 제목에 값넣기
title = slide.shapes.title  # 제목
title.text = "주식 보고서"  # 제목에 값 넣기
# 부제목
subtitle = slide.placeholders[1]  # 제목상자는 placeholders[0], 부제목상자는 [1]
subtitle.text = "보고서 작성일 : {date}".format(date=today)

#################################
예제 #48
0
import pandas as pd
from pptx import Presentation
from pptx import slide


#파일 불러오기
file_list =pd.read_csv('c:/', names=[], header=[], index_col=)
#file_list = pd.read_excel(''. sheetname=)

pic_dir = './picture'
picture_list = os.listdir(pic_dir)
#picture_list = df[].tolist()
pptx_dir = './ppt'
pptx_list = os.listdir(pptx_dir)
for pt in pptx_list:
    prs = Presentation('%s' %(fileName))

    slides = prs.slides
    print(len(slides))

    for i in picture_list:
        for idx in range(len(slides)):
            #print(slides[idx].shapes)
            slide = slides[idx]
            for shape in slide.placeholders:
                print('%d %s' % (shape.placeholder_format.idx, shape.name))
                picture = slide.placeholders[1].insert_picture('./picture/%s' % (i))


#파일로 저장(새파일로 하기)
    prs.save('PI_'+pt)
예제 #49
0
from pptx import Presentation
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches
from pptx.dml.color import RGBColor
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 = ['Q1 Sales', 'Q2 Sales', 'Q3 Sales']
chart_data.add_series('West', (32.2, 28.4, 34.7))
chart_data.add_series('East', (24.3, 30.6, 20.2))
chart_data.add_series('Midwest', (20.4, 18.3, 26.2))

# 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.LINE, x, y, cx, cy,
                               chart_data).chart

# define axis and labels --------------
chart.has_legend = True
chart.legend.include_in_layout = False
chart.series[0].smooth = True

prs.save('lineChart.pptx')
예제 #50
0
plt.legend()
plt.savefig('D:\\reports\\pic\\1.png')

# pic 2: implied vol and rolling 5 day volatility
plt.figure()
sh510050['vol_10d'].plot(label = '10 days vol')
ivix['close'].plot(label = 'implied vol')
plt.legend()
plt.savefig('D:\\reports\\pic\\2.png')

# performance of all assets



# create ppt file
prs = Presentation('D:\\reports\\templet\\templet.pptx')

# page 1
layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(layout)
title = slide.shapes.title
subtitle = slide.placeholders[1]
title.text = "Weekly Report"
subtitle.text = "Generated on {:%Y-%m-%d}".format(date.today())

# page 2
layout1 = prs.slide_layouts[1]
slide = prs.slides.add_slide(layout1)
title = slide.shapes.title
title.text = u"上证50 & IVIX "
placeholder = slide.placeholders[1]
예제 #51
0
def given_a_FillFormat_object_as_fill(context):
    fill = Presentation(test_pptx("dml-fill")).slides[0].shapes[0].fill
    context.fill = fill
예제 #52
0
 def set_presentation(self):
     self.__presentation = Presentation(self.__filename)
예제 #53
0
def make_pptx(odbname, dict_o_c, list_v):
    """ Generic Function to create a pptx file
        filename = relative path with directories, eg temp0/beam_tutorial.odb
       creates a new pptx file and inserts all the images in the current directory
       ppt default width 10 inches by 7.5 inches landscape
       #odbname = 'customBeamExample/customBeamExample.odb'

        # make a new slide for each component given
        dict_o_c = {'S':['Mises'], 'U':['U1','Magnitude'],  'RF':['RF1'], 'EVOL':['']}

        # add all three views onto the same slide
        list_v = ['Iso','Left','Top']

        CBE_make_pptx(odbname,dict_o_c,list_v)
       """
    def img_insert(imgtyp='', picname=''):
        """functions for inserting standard images"""
        try:
            if imgtyp == 'icon':
                left = Inches(0.05)
                top = Inches(6.85)
                slide.shapes.add_picture(
                    'https://www.python.org/static/img/python-logo.png', left,
                    top)
            elif imgtyp[:3] == 'Iso':
                left = Inches(6)
                top = Inches(4.25)
                myHeight = Inches(2.5)
                slide.shapes.add_picture(picname, left, top, height=myHeight)
            elif imgtyp == 'Top':
                left = Inches(6)
                top = Inches(2.0)
                myHeight = Inches(2.5)
                slide.shapes.add_picture(picname, left, top, height=myHeight)
            elif imgtyp == 'Left':
                left = Inches(8.2)
                top = Inches(5.8)
                myHeight = Inches(1)
                slide.shapes.add_picture(picname, left, top, height=myHeight)
            elif imgtyp == 'gif':
                left = Inches(0.1)
                top = Inches(2.7)
                myHeight = Inches(4)
                slide.shapes.add_picture(picname, left, top, height=myHeight)
            elif imgtyp == 'main':
                left = Inches(1.9)
                top = Inches(2.5)
                myHeight = Inches(4)
                slide.shapes.add_picture(picname, left, top, height=myHeight)
            else:
                pass
        except:
            print('failed to insert image %s' % picname)

    #odbname = 'customBeamExample/customBeamExample.odb'
    pptx1 = Presentation()
    #blank_slide_layout = pptx1.slide_layouts[6]
    bullet_slide_layout = pptx1.slide_layouts[1]
    title_slide_layout = pptx1.slide_layouts[0]
    title_only_layout = pptx1.slide_layouts[5]

    # first slide #####################################################################################################
    slide = pptx1.slides.add_slide(title_slide_layout)
    slide.shapes.title.text = "test report generation"
    slide.placeholders[
        1].text = '''Automatic Report Generation Using Python by '''
    left = Inches(4)
    top = Inches(5.5)
    slide.shapes.add_picture(
        'https://www.python.org/static/img/python-logo.png', left, top)

    # second slide #####################################################################################################
    slide = pptx1.slides.add_slide(bullet_slide_layout)
    shapes = slide.shapes
    title_shape = shapes.title
    body_shape = shapes.placeholders[1]
    title_shape.text = 'Simualtion Overview'
    tf = body_shape.text_frame
    tf.text = 'A script was created to run a simulation and generate results'

    p = tf.add_paragraph()
    p.text = 'The script was written in python'
    p.level = 1

    p = tf.add_paragraph()
    p.text = 'The script builds the model, sets up the boundary and loading \
    conditions, runs the simulation, extracts data for plotting, and \
    contour plots or model images'

    p.level = 0

    p = tf.add_paragraph()
    p.text = 'The same script can be adapted to more \
    complex simulations'

    p.level = 0

    left = top = width = height = Inches(1.5)

    # Third Slide #####################################################################################################
    slide = pptx1.slides.add_slide(title_only_layout)
    title_shape = slide.shapes.title
    img_insert('icon')
    title_shape.text = 'Underformed Mesh'
    txBox = slide.shapes.add_textbox(left, top, width, height)
    txBox.text_frame.text = "Element boundaries have been removed to show the undeformed \n shape of the model"
    picnames = glob.glob(os.path.dirname(odbname) + '/*.png')
    if picnames:
        picname = [f for f in picnames if 'Undeformed' in f]
        if picname:
            img_insert('main', picname[0])

    # Field slides #####################################################################################################
    for o in dict_o_c:
        for c in dict_o_c[o]:
            slide = pptx1.slides.add_slide(title_only_layout)
            title_shape = slide.shapes.title
            img_insert('icon')
            title_shape.text = o + '-' + c
            txBox = slide.shapes.add_textbox(left, top, width, height)
            txBox.text_frame.text = "This is text inside a textbox\n and this is some more text that you can add"
            for v in list_v:
                picnames = glob.glob(os.path.dirname(odbname) + '/*.png')
                if picnames:
                    picname = [
                        f for f in picnames if o in f if c in f if v in f
                    ]
                    if picname:
                        img_insert(v, picname[0])
            picnames = glob.glob(os.path.dirname(odbname) + '/*.gif')
            if picnames:
                picname = [
                    f for f in picnames if o in f if c in f if 'Iso' in f
                ]
                if picname:
                    img_insert('gif', picname[0])

    # save pptx
    pptx1.save(os.path.splitext(odbname)[0] + '.pptx')
예제 #54
0
def clear_metadata(src, dst):
    src = settings.LEADING_SLASH + src
    dst = settings.LEADING_SLASH + dst
    ext = os.path.splitext(dst)[1]  # assumed to be in lower case!
    meta_fields = [
        'author', 'category', 'comments', 'content_status', 'identifier',
        'keywords', 'last_modified_by', 'language', 'subject', 'title',
        'version'
    ]
    try:
        if ext in ['.docx']:
            f = open(src, 'rb')
            doc = Document(f)
            f.close()
            for meta_field in meta_fields:
                setattr(doc.core_properties, meta_field, '')
            setattr(doc.core_properties, 'created', DEFAULT_DATE)
            setattr(doc.core_properties, 'modified', DEFAULT_DATE)
            setattr(doc.core_properties, 'last_printed', DEFAULT_DATE)
            setattr(doc.core_properties, 'revision', 1)
            doc.save(dst)
            clean_xml_in_zip(dst)
        elif ext in ['.pptx']:
            prs = Presentation(src)
            for meta_field in meta_fields:
                setattr(prs.core_properties, meta_field, '')
            setattr(prs.core_properties, 'created', DEFAULT_DATE)
            setattr(prs.core_properties, 'modified', DEFAULT_DATE)
            setattr(prs.core_properties, 'last_printed', DEFAULT_DATE)
            setattr(prs.core_properties, 'revision', 1)
            prs.save(dst)
            clean_xml_in_zip(dst)
        elif ext == '.pdf':
            fin = file(src, 'rb')
            inp = PdfFileReader(fin)
            outp = PdfFileWriter()
            for page in range(inp.getNumPages()):
                outp.addPage(inp.getPage(page))
            infoDict = outp._info.getObject()
            infoDict.update({
                NameObject('/Title'): createStringObject(u''),
                NameObject('/Author'): createStringObject(u''),
                NameObject('/Subject'): createStringObject(u''),
                NameObject('/Creator'): createStringObject(u'')
            })
            fout = open(dst, 'wb')
            outp.write(fout)
            fin.close()
            fout.close()
        elif ext == '.xlsx':
            file_to_clear = 'docProps/core.xml'
            # create a copy of the Excel file while "cleaning" docProps/core.xml
            with ZipFile(src, 'r') as src_zip:
                with ZipFile(dst, 'w') as dst_zip:
                    dst_zip.comment = src_zip.comment  # preserve the comment (if any)
                    for item in src_zip.infolist():
                        if item.filename == file_to_clear:
                            # read the XML tree from the file
                            xml = src_zip.read(item.filename)
                            xml = re.sub(r'<dc:title>[^<]{1,1000}</dc:title>',
                                         '<dc:title></dc:title>', xml)
                            xml = re.sub(
                                r'<dc:subject>[^<]{1,500}</dc:subject>',
                                '<dc:subject></dc:subject>', xml)
                            xml = re.sub(
                                r'<dc:creator>[^<]{1,300}</dc:creator>',
                                '<dc:creator></dc:creator>', xml)
                            xml = re.sub(
                                r'<dc:description>[^<]{1,2500}</dc:description>',
                                '<dc:description></dc:description>', xml)
                            xml = re.sub(
                                r'<cp:keywords>[^<]{1,1000}</cp:keywords>',
                                '<cp:keywords></cp:keywords>', xml)
                            xml = re.sub(
                                r'<cp:lastModifiedBy>[^<]{1,300}</cp:lastModifiedBy>',
                                '<cp:lastModifiedBy></cp:lastModifiedBy>', xml)
                            xml = re.sub(
                                r'<cp:category>[^<]{1,300}</cp:category>',
                                '<cp:category></cp:category>', xml)
                            xml = re.sub(
                                r'<cp:contentStatus>[^<]{1,100}</cp:contentStatus>',
                                '<cp:contentStatus></cp:contentStatus>', xml)
                            xml = re.sub(
                                r'<cp:revision>[^<]{1,10}</cp:revision>',
                                '<cp:revision></cp:revision', xml)
                            # replace all date-time fields with the default date
                            xml = re.sub(
                                r':W3CDTF">[^<]{1,25}</dcterms:',
                                ':W3CDTF">2001-01-01T00:00:00Z</dcterms:', xml)
                            dst_zip.writestr(item, xml)
                        else:
                            dst_zip.writestr(item, src_zip.read(item.filename))
    except Exception, e:
        log_message('Exception while removing metadata from a %s file: %s' %
                    (ext, str(e)))
예제 #55
0
# pptx = Presentation(pptdir)
# # 遍历ppt文件的所有幻灯片页
# for slide in pptx.slides:
#     # 遍历幻灯片页的所有形状
#     print(1)
#     for shape in slide.shapes:
#     # 判断形状是否含有文本框,如果含有则顺序运行代码
#         if shape.has_text_frame:
#             # 获取文本框
#             text_frame = shape.text_frame
#             # 遍历文本框中的所有段落
#             for paragraph in text_frame.paragraphs:
#                 # 将文本框中的段落文字写入word中
#                 print(paragraph.text)

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 = 'Hello world!'
subtitle.text = 'python-pptx was here.'

prs.save(cwd + r'\test.pptx')

pptfile = cwd + r'\test.pptx'

# print(pptfile)
png_folder = cwd + r'\temp'
#png_folder = cwd +r'\1.png'
예제 #56
0
# ファイル選択ダイアログの表示
root = tkinter.Tk()
root.withdraw()
fTyp = [("", "*.jpg"), ("", "*.png")]
iDir = os.path.abspath(os.path.dirname(__file__))
#tkinter.messagebox.showinfo('○×プログラム','処理ファイルを選択してください!')

# ここの1行を変更 askopenfilename → askopenfilenames
file = tkinter.filedialog.askopenfilenames(filetypes=fTyp, initialdir=iDir)

# 選択ファイルリスト作成
#list = list(file)
#tkinter.messagebox.showinfo('○×プログラム',list)

prs = Presentation("template.pptx")
max_height = Cm(19.05)
max_width = Cm(33.867)
for i in range(len(file)):
    layout = prs.slide_layouts[6]  # 6 白紙
    slide = prs.slides.add_slide(layout)
    img = Image.open(file[i])
    if img.width / img.height > 16 / 9:
        pic = slide.shapes.add_picture(file[i], 0, 0, width=max_width)
    else:
        pic = slide.shapes.add_picture(file[i], 0, 0, height=max_height)

prs.save("a.pptx")
subprocess.Popen([
    r"C:\Program Files\Microsoft Office\root\Office16\POWERPNT.EXE", r"a.pptx"
])
예제 #57
0
def given_a_chevron_shape(context):
    prs = Presentation(test_pptx('shp-autoshape-adjustments'))
    context.shape = prs.slides[0].shapes[0]
예제 #58
0
def given_a_shape_of_known_position_and_size(context):
    prs = Presentation(test_pptx('shp-pos-and-size'))
    context.shape = prs.slides[0].shapes[0]
예제 #59
0
def given_an_autoshape_having_text(context):
    prs = Presentation(test_pptx('shp-autoshape-props'))
    context.shape = prs.slides[0].shapes[0]
예제 #60
0
def given_a_connector(context):
    prs = Presentation(test_pptx('shp-common-props'))
    sld = prs.slides[0]
    context.shape = sld.shapes[4]