Python pptx.Presentation() Examples

The following are 17 code examples of pptx.Presentation(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pptx , or try the search function .
Example #1
Source File: report.py    From reportgen with MIT License 6 votes vote down vote up
def __init__(self,filename=None,chart_type_default='COLUMN_CLUSTERED',**kwargs):
        self.title=None
        self.author=None
        # self.filename = filename #导入一个存在的pptx文件
        self.chart_type_default=chart_type_default
        if filename is None:
            if os.path.exists('template.pptx'):
                prs=Presentation('template.pptx')
            elif template_pptx is not None:
                prs=Presentation(template_pptx)
            else:
                prs=Presentation()
        else :
            # 分离出路径中的文件名
            self.title=os.path.splitext(os.path.split(filename)[1])[0]
            prs=Presentation(filename)
        self.prs=prs
        title_only_slide=self._layouts()
        if title_only_slide:
            layouts=title_only_slide[0]
        else:
            layouts=[0,0]
        self.layouts_default=layouts
        for k in kwargs:
            setattr(self,k.lower(),kwargs[k]) 
Example #2
Source File: main.py    From lambda-text-extractor with Apache License 2.0 6 votes vote down vote up
def pptx_to_text(document_path, event, context):
    import pptx

    prs = pptx.Presentation(document_path)

    paragraphs = []

    for slide in prs.slides:
        for shape in slide.shapes:
            if not shape.has_text_frame: continue
            paragraphs += [' '.join([run.text for run in paragraph.runs]) for paragraph in shape.text_frame.paragraphs]
        #end for
    #end for

    return '\n\n'.join(paragraphs).strip()
#end def 
Example #3
Source File: image_viewer.py    From pandasgui with MIT License 6 votes vote down vote up
def ppt_section_slide(title, subtitle, file_path):
    from pptx import Presentation
    try:
        prs = Presentation(file_path)
    except:
        prs = Presentation(r'C:\Users\adrose\Desktop\AMD PowerPoint Template.pptx')
    picture_slide_layout = prs.slide_layouts[0]
    slide = prs.slides.add_slide(picture_slide_layout)

    # for x in slide.placeholders:
    #     print('%d %s' % (x.placeholder_format.idx, x.name))

    title_placeholder = slide.placeholders[0]
    subtitle_placeholder = slide.placeholders[1]

    title_placeholder.text = title
    subtitle_placeholder.text = subtitle

    prs.save(file_path) 
Example #4
Source File: pd2ppt.py    From PandasToPowerpoint with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #5
Source File: generator.py    From talk-generator with MIT License 6 votes vote down vote up
def generate_presentation_using_cli_arguments(args) -> Tuple[Presentation, SlideDeck, str]:
    """Make a talk with the given topic."""

    runtime_checker.check_runtime_environment()

    # Print status details
    logger.info("******************************************")
    logger.info("Making {} slide talk on: {}".format(args.num_slides, args.topic))

    return generate_presentation(
        schema=args.schema,
        slides=args.num_slides,
        topic=args.topic,
        title=args.title,
        presenter=args.presenter,
        parallel=args.parallel,
        int_seed=args.int_seed,
        print_logs=args.print_logs,
        save_ppt=args.save_ppt,
        open_ppt=args.open_ppt,
    ) 
Example #6
Source File: visual_editor.py    From quantipy with MIT License 5 votes vote down vote up
def rename_duplicate_shape_names(pres_path, overwrite=True):
    ''' 
    Ensures all shapes have a unique name. 
    Only renames duplicates. 
    Compares shape names one slide at a time. 
    '''

    file_name = basename(pres_path).split('.')[0]
    file_path = dirname(pres_path)

    prs = Presentation(pres_path)

    for slide in prs.slides:
        shape_names = []
        for shape in slide.shapes:
            shape_names.append(shape.name)
        renamed_shapes = [x + "_" + str(i) if shape_names.count(x)>1 else x for i, x in enumerate(shape_names)]
        for s_idx, shape in enumerate(slide.shapes):
            shape.name = renamed_shapes[s_idx]

    if overwrite:
        prs.save('{pres_path}\\{pres_name}.pptx'.format(
            pres_path=file_path, 
            pres_name=file_name))
    else:
        prs.save('{pres_path}\\{pres_name}_edited.pptx'.format(
            pres_path=file_path, 
            pres_name=file_name)) 
Example #7
Source File: visual_editor.py    From quantipy with MIT License 5 votes vote down vote up
def get_chart_data_from_prs(pres_path, slide_num, chart_name):
    '''
    This function 1) pulls a given chart's data and 2) returns it as a pandas dataframe object in a list
    
    param: pres_path - full path of target file
    param: slide_num - takes a list of slides 
    param: chart_name - object name as it appears within powerpoint's Object Selection Pane
    '''
    
    prs = Presentation(pres_path)
    
    collection_of_dfs = []

    for i, sld in enumerate(prs.slides, start=1):
        if i in slide_num: 
            for x, shp in enumerate(sld.shapes):
                
                if shp.name == chart_name:
                    
                    plot = shp.chart.plots[0]

                    columns = []
                    data = []
                    for series in plot.series:
                        columns.append(str(series.name))
                        data.append(series.values)
                  
                    data = np.array(data)
                    rows = np.array(plot.categories)
                      
                    df = pd.DataFrame(data.T, index=rows, columns=columns)    
                    collection_of_dfs.append(df)

    return(collection_of_dfs) 
Example #8
Source File: visual_editor.py    From quantipy with MIT License 5 votes vote down vote up
def replace_chart_data_in_prs(pres_path, slide_num, chart_name, df):
    '''
    This function 1) enters an existing powerpoint, 2) finds given slides, 3) finds given chart by name and
    4) replaces the given chart's underlying data with new data in the form of a dataframe. 

    param: pres_path - takes the full path of target file
    param: slide_num - takes a list of slides 
    param: chart_name - object name as it appears within powerpoint's Object Selection Pane
    param: df - takes a list of pandas dataframe objects 
    '''
    
    PRES_FOLDER_FOLDER = dirname(pres_path)
    PRES_NAME = basename(pres_path).replace('.pptx','')
    
    prs = Presentation(pres_path)
    
    loop_counter=0

    for i, sld in enumerate(prs.slides, start=1):
        if i in slide_num:
            for x, shp in enumerate(sld.shapes):

                if shp.name == chart_name:

                    single_df = df[loop_counter]
                    chart_data = ChartData()
                    chart_data.categories = single_df.index
 
                    for col_idx, col in enumerate(single_df.columns):
                        chart_data.add_series(col, (single_df.ix[:, col_idx].values))            
                     
                    shp.chart.replace_data(chart_data)
                    
            loop_counter+=1
                
    prs.save('{pres_path}\\{pres_name}_edited.pptx'.format(
            pres_path=PRES_FOLDER_FOLDER, 
            pres_name=PRES_NAME)) 
Example #9
Source File: pptx_util.py    From convnet-drawer with MIT License 5 votes vote down vote up
def __init__(self):
        self.presentation = Presentation(os.path.join(os.path.dirname(__file__), "template.pptx"))
        self.slide_layout = self.presentation.slide_layouts[6]
        self.slide = self.presentation.slides.add_slide(self.slide_layout)
        self.shapes = self.slide.shapes 
Example #10
Source File: pic_to_ppt.py    From crawlBaiduWenku with MIT License 5 votes vote down vote up
def pic_to_ppt(filename):  #前提是图片文件名全为数字,否则还需要修改
    if not os.path.exists(filename):
        os.mkdir(filename)
    
    ppt = pptx.Presentation()
    pic_path=[]  
    for i in os.walk(filename).__next__()[2]:
        if i.endswith('.png'):
            pic_path.append(i)
    #若是不全为数字,则可尝试运行下列代码
#    ls=[]
#    for png in pic_path:
#        s=''
#        for item in png:
#            if item<='9' and item>='0':
#                s+=item
#        ls.append(s+'.png')
#    pic_path=ls
    
    pic_path.sort(key=lambda item:int(item.split('.')[0]))
    for i in pic_path:
        i='{}/{}'.format(filename,i)
        slide = ppt.slides.add_slide(ppt.slide_layouts[1])
        slide.shapes.add_picture(i, Inches(0), Inches(0), Inches(10), Inches(7.5))
        
    fname='{}/{}.pptx'.format(filename,filename)
    ppt.save(fname)
    print('生成的文件在 {} 文件夹下的 {}.ppt 中'.format(filename,filename)) 
Example #11
Source File: PptxPainterClass.py    From quantipy with MIT License 5 votes vote down vote up
def __init__(self, path_to_presentation, slide_layout=None, shape_properties=None):

        self.presentation  = Presentation(path_to_presentation) # TODO PptxPainter - Path checking # type: Presentation
        if slide_layout is None:
            self.default_slide_layout = None
        else:
            self.default_slide_layout = self.set_slide_layout(slide_layout)

        # Add all the dafault dicts to the class -
        if shape_properties:
            self._shape_properties = shape_properties
        else:
            self._shape_properties = PptxDefaults()

        self.textbox = self._shape_properties.textbox
        self.textbox_header = self._shape_properties.textbox_header
        self.textbox_footer = self._shape_properties.textbox_footer
        self.chart = self._shape_properties.chart
        self.table = self._shape_properties.table
        self.side_table = self._shape_properties.side_table

        charts = self._shape_properties.charts
        self.chart_bar = charts['bar']
        self.chart_bar_stacked100 = charts['bar_stacked100']
        self.chart_line = charts['line']
        self.chart_column = charts['column']
        self.chart_pie = charts['pie']

        self.slide_kwargs = {
                    'textboxs': {},
                    'charts': {},
                    'tables': {},
                    'side_tables': {},
                    } 
Example #12
Source File: cli.py    From pptx-template with Apache License 2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description = 'Edit pptx with text replace and csv import')
    parser.add_argument('--template',  help='template pptx file (required)', required=True)
    parser.add_argument('--model',     help='model object file with .json or .xlsx format', required=True)
    parser.add_argument('--out',       help='created pptx file (required)', required=True)
    parser.add_argument('--debug',     action='store_true', help='output verbose log')
    parser.add_argument('--skip-model-not-found', action='store_true', help='skip if specified key is not found in the model')
    opts = parser.parse_args()

    if not len(log.handlers):
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)
        log.addHandler(handler)

    if opts.debug:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)

    log.info(u"pptx-template version %s" % __version__)

    if opts.model.endswith(u'.xlsx'):
        slides = generate_whole_model(opts.model, {})
    else:
        if opts.model == u'-' and sys.version_info[0] == 3:
            sys.stdin = TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
        with open(opts.model, 'r', encoding='utf-8') if opts.model != u'-' else sys.stdin as m:
            models = json.load(m)
        slides = models[u'slides']

    log.info(u"Loading template pptx: %s" % opts.template)
    ppt = Presentation(opts.template)
    process_all_slides(slides, ppt, skip_model_not_found = opts.skip_model_not_found)

    log.info(u"Writing pptx: %s" % opts.out)
    ppt.save(opts.out) 
Example #13
Source File: CVE-2014-4114.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #14
Source File: utility.py    From pandasgui with MIT License 5 votes vote down vote up
def save_figs_to_ppt(figs, filename):
    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!"

    prs.save('test.pptx') 
Example #15
Source File: powerpoint_slide_creator.py    From talk-generator with MIT License 5 votes vote down vote up
def create_new_powerpoint() -> Presentation:
    return Presentation(get_powerpoint_template_file()) 
Example #16
Source File: report.py    From reportgen with MIT License 4 votes vote down vote up
def df_to_table(slide,df,left,top,width,height,index_names=False,columns_names=True):
    '''将pandas数据框添加到slide上,并生成pptx上的表格
    输入:
    slide:PPT的一个页面,由pptx.Presentation().slides.add_slide()给定
    df:需要转换的数据框
    lef,top: 表格在slide中的位置
    width,height: 表格在slide中的大小
    index_names: Bool,是否需要显示行类别的名称
    columns_names: Bool,是否需要显示列类别的名称
    返回:
    返回带表格的slide
    '''
    df=pd.DataFrame(df)
    rows, cols = df.shape
    res = slide.shapes.add_table(rows+columns_names, cols+index_names, left, top, width, height)
    # 固定表格的宽度
    '''
    for c in range(cols+rownames):
        res.table.columns[c].width = colwidth
        res.table.rows[c].width = colwidth
    '''
    # Insert the column names
    if columns_names:
        for col_index, col_name in enumerate(list(df.columns)):
            cell=res.table.cell(0,col_index+index_names)
            #cell.text_frame.fit_text(max_size=12)
            #cell.text_frame.text='%s'%(col_name)
            cell.text = '%s'%(col_name)
    if index_names:
        for col_index, col_name in enumerate(list(df.index)):
            cell=res.table.cell(col_index+columns_names,0)
            cell.text = '%s'%(col_name)
            #cell.text_frame.fit_text(max_size=12)
    m = df.as_matrix()
    for row in range(rows):
        for col in range(cols):
            cell=res.table.cell(row+columns_names, col+index_names)
            if isinstance(m[row, col],float):
                cell.text = '%.2f'%(m[row, col])
            else:
                cell.text = '%s'%(m[row, col])
            #cell.text_frame.fit_text(max_size=12) 
Example #17
Source File: image_viewer.py    From pandasgui with MIT License 4 votes vote down vote up
def to_ppt_slide(fig, file_path, append=False, padding=0.5):
    from io import StringIO, BytesIO
    import pptx
    from pptx import Presentation
    from pptx.util import Inches

    # Create in-memory image stream and save figure to it
    image_stream = BytesIO()
    fig.savefig(image_stream)

    if append:
        try:
            # Try opening the file if it already exists
            prs = Presentation(file_path)
        except pptx.exc.PackageNotFoundError:
            prs = Presentation()
    else:
        prs = Presentation()
    # Create a new slide with the blank template
    blank_slide_layout = prs.slide_layouts[6]
    slide = prs.slides.add_slide(blank_slide_layout)

    # Center image without changing its aspect ratio
    slide_width = prs.slide_width.inches - 2 * padding
    slide_height = prs.slide_height.inches - 2 * padding
    fig_width, fig_height = fig.get_size_inches()
    if (fig_width / slide_width) > (fig_height / slide_height):
        # Image fits slide horizontally and must be scaled down vertically
        width = slide_width
        height = width * fig_height / fig_width
        top = padding + (slide_height - height) / 2
        left = padding
    else:
        # Image fits slide vertically and must be scaled down horizontally
        height = slide_height
        width = height * fig_width / fig_height
        left = padding + (slide_width - width) / 2
        top = padding

    # Convert from EMU to inches
    left = Inches(left)
    top = Inches(top)
    height = Inches(height)
    width = Inches(width)

    pic = slide.shapes.add_picture(image_stream, left, top, height=height, width=width)

    prs.save(file_path)