本文整理汇总了Python中pptx.Presentation类的典型用法代码示例。如果您正苦于以下问题:Python Presentation类的具体用法?Python Presentation怎么用?Python Presentation使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Presentation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
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: PptManager
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: to_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
示例4: df_to_powerpoint
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: main
def main(trac_id, trac_pass, this_round):
pptfile = '%s_tickets.pptx' % this_round
print('\n' + pptfile)
trac_rpc_url = 'http://%s:%[email protected]%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
示例6: image_folder2pptx
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: main
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')
示例8: create_presentation
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)
示例9: analyze_ppt
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)
示例10: __call__
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: create_ppt
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: main
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: parse_csv_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)
示例14: CreatePPT
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))
示例15: pptRep
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)