def set_slide_size(prs: Presentation, width: float = 26, height: float = 15) -> Presentation: """set the size of all slides in cm""" prs.slide_width = Cm(width) prs.slide_height = Cm(height) return prs
def create_presentation_with_branding_image(image_paths, n_slide): prs = Presentation() prs.slide_width = Inches(10) prs.slide_height = Inches(6) blank_slide_layout = prs.slide_layouts[6] for i in range(n_slide): slide = prs.slides.add_slide(blank_slide_layout) left = top = 0 if i == 0: slide.shapes.add_picture(image_paths[0], left, top, width=prs.slide_width, height=prs.slide_height) elif i == 1: slide.shapes.add_picture(image_paths[1], left, top, width=prs.slide_width, height=prs.slide_height) else: slide.shapes.add_picture(image_paths[2], left, top, width=prs.slide_width, height=prs.slide_height) return prs
def create_ppt(self): # self.log.info('Called create_ppt') prs = Presentation() prs.slide_height = Inches(9) prs.slide_width = Inches(16) 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 = Inches(0.3) top = Inches(0.5) height = Inches(7.8) pic = slide.shapes.add_picture(img_path, left, top, height=height) prs.save(self.ppt_file) except IOError: pass
def make_presentation(slides_dir_path, presentation_title): full_slide_paths = [slides_dir_path + slide_path for slide_path in sorted(listdir(slides_dir_path))] height, width, channels = imread(full_slide_paths[0]).shape height_inch = 0.010416666666819 * height width_inch = 0.010416666666819 * width presentation = Presentation() presentation.slide_height = Inches(height_inch) presentation.slide_width = Inches(width_inch) first_slide = presentation.slides.add_slide(presentation.slide_layouts[6]) first_slide.background.fill.solid() first_slide.background.fill.fore_color.rgb = RGBColor(224, 22, 120) preface = first_slide.shapes.add_textbox(left=Inches((width_inch - 3)/2), top=Inches((height_inch - 1.2)/2), height=Inches(1.2), width=Inches(3)) title = preface.text_frame.add_paragraph() title.text = "Automation 101" title.alignment = PP_ALIGN.CENTER title.font.bold = True title.font.size = Pt(30) title.font.color.rgb = RGBColor(255, 255, 255) creds = preface.text_frame.add_paragraph() creds.text = "by bex on the beach" creds.alignment = PP_ALIGN.CENTER creds.font.color.rgb = RGBColor(209, 203, 207) for slide_path in full_slide_paths: curr_slide = presentation.slides.add_slide(presentation.slide_layouts[6]) curr_slide.shapes.add_picture(slide_path, left=Inches(0), top=Inches(0), height=Inches(height_inch), width=Inches(width_inch)) presentation.save('{0}{1}.pptx'.format(slides_dir_path, presentation_title))
def make_spreadsheet_for_all(city, years=None): from pptx import Presentation from pptx.util import Inches left = Inches(0.44) top = Inches(0.46) width = Inches(9) prs = Presentation() prs.slide_width=Inches(10) prs.slide_height= Inches(5.625) blank_slide_layout = prs.slide_layouts[6] demographics_per_page = 3 demo_pages = range(0,math.ceil(len(demographics)/demographics_per_page)) BASE_DIR = VIS_DIR / 'figures' / city.BASE_NAME BASE_DIR.mkdir(parents=True, exist_ok=True) blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) slide.shapes.add_picture(str(BASE_DIR / 'all.png'), left, top, width=width) for i in demo_pages: slide = prs.slides.add_slide(blank_slide_layout) slide.shapes.add_picture(str(BASE_DIR / 'all_demos_{}.png'.format(i)), left, top, width=width) if not years: years = city.processed_data.year.unique() for year in years: print('doing year', year ) slide = prs.slides.add_slide(blank_slide_layout) slide.shapes.add_picture(str( BASE_DIR / 'all_{}.png'.format(year)), left, top,width=width) for i in demo_pages: slide = prs.slides.add_slide(blank_slide_layout) slide.shapes.add_picture(str( BASE_DIR / 'all_{}_demos_{}.png'.format(year,i)), left, top,width=width) for crime in city.processed_data.call_type.unique(): print('doing cime, crime') try: slide = prs.slides.add_slide(blank_slide_layout) if(crime == None): slide.shapes.add_picture(str(BASE_DIR / 'other.png'), left, top, width=width) else: slide.shapes.add_picture(str(BASE_DIR / '{}.png'.format(crime.replace(" ","_").replace("/","_"))), left, top, width=width) for i in demo_pages: slide = prs.slides.add_slide(blank_slide_layout) if(crime == None): slide.shapes.add_picture(str(BASE_DIR / 'other_demos_{}.png').format(i), left, top, width=width) else: slide.shapes.add_picture(str(BASE_DIR / '{}_demos_{}.png'.format(crime.replace(" ","_").replace("/","_"),i)), left, top, width=width) except: print('issue with ', crime) prs.save(str(VIS_DIR / 'summaries_{}.pptx'.format(city.BASE_NAME)))
def __init__(self, background_style='default', width=16, height=9): prs = Presentation() prs.slide_width = Inches(width) # Slide宽度 16 Inches, 高度 9 Inches 16:9 prs.slide_height = Inches(height) self.width = width self.height = height blank_slide_layout = prs.slide_layouts[6] # index 6 是空白slide预设 slide = prs.slides.add_slide(blank_slide_layout) # 添加slide self.__prs__ = prs self.canvas = slide.shapes self.background = Background(background_style=background_style, sign=self) self.background.draw()
def create_title_slide(ppt_fpath, title="", subtitle=""): """ Create a ppt presentation by generating a title slide and saving it. Parameters ---------- ppt_fpath: pathlib.Path Absolute path of location to save the ppt. Must be a pathlib Path object, not a str title: str The text you want to be in the title box. Default is empty subtitle: str The text you want to be in the subtitle box. Default is empty Returns ------- """ """if not ppt_fpath.endswith(".pptx"): ppt_fpath += ".pptx""" "" # This does not work on Windows, uncomment if on other system and comment # out section below ppt_fpath.touch( ) # some of the windows functions require the file to exist if ".pptx" not in str(ppt_fpath): ppt_fpath.unlink() # Delete the temp file ppt_fpath = ppt_fpath.parent / (ppt_fpath.name + ".pptx") # Rename ppt_fpath.touch() # Create the new file # Create a presentation object. The default size for this package is not a usual slide size, so you have to modify prs = Presentation() prs.slide_width = Inches(16) prs.slide_height = Inches(9) # There are set slide layouts. The title slide is not all that important, so we just choose the default one title_slide_layout = prs.slide_layouts[0] slide = prs.slides.add_slide(title_slide_layout) # Access the title textbox and add your text title_txtbox = slide.shapes.title title_txtbox.text = title # Access the subtitle textbox and add your text subtitle_txtbox = slide.placeholders[1] subtitle_txtbox.text = subtitle prs.save(ppt_fpath)
def imgs2powerpoint(outpath): prs = Presentation() img = Image.open("Images/Picture1.png") width, height = img.size prs.slide_width = Inches(width / 500) prs.slide_height = Inches(height / 500) blank_slide_layout = prs.slide_layouts[6] imagelist = os.listdir("Images/") for image in natsort.natsorted(imagelist): slide = prs.slides.add_slide(blank_slide_layout) left = top = 0 slide.shapes.add_picture("Images/{}".format(image), left, top, height=prs.slide_height, width=prs.slide_width) prs.save(outpath)
def convert(pdf_file): print() print("Converting file: " + pdf_file) print() # Prep presentation prs = Presentation() blank_slide_layout = prs.slide_layouts[6] # Create working folder base_name = pdf_file.split(".pdf")[0] # Convert PDF to list of images print("Starting conversion...") slideimgs = convert_from_path(pdf_file, 300, fmt='ppm', thread_count=2) print("...complete.") print() # Loop over slides for i, slideimg in enumerate(slideimgs): if i % 10 == 0: print("Saving slide: " + str(i)) imagefile = BytesIO() slideimg.save(imagefile, format='tiff') imagedata = imagefile.getvalue() imagefile.seek(0) width, height = slideimg.size # Set slide dimensions prs.slide_height = height * 9525 prs.slide_width = width * 9525 # Add slide slide = prs.slides.add_slide(blank_slide_layout) pic = slide.shapes.add_picture(imagefile, 0, 0, width=width * 9525, height=height * 9525) # Save Powerpoint print() print("Saving file: " + base_name + ".pptx") prs.save(base_name + '.pptx') print("Conversion complete. :)") print()
def pdf2pptBT(): lblpdftopptBTN.config(text="Working!") files = filedialog.askopenfiles() p = str(files[0].name).replace("/", "\\").rsplit('\\', 1)[0] os.chdir(p) for x in files: presentation = Presentation() path = str(x.name).replace("/", "\\") print(path) name = path.split("\\")[-1] print(name) promp1 = "Select DPI, default 600 (over 1000 the program will freak out, recommended 300 - 800)" DPI = simpledialog.askstring(title="DPI", prompt=promp1) promp2 = "Select number of threads, default 4 (recommended 2 - 4)" threads = simpledialog.askstring(title="No. of Threads", prompt=promp2) if DPI == "" and threads != "": si = convert_from_path(name, 600, thread_count=int(threads)) elif DPI == "" and threads == "": si = convert_from_path(name, 600, thread_count=4) else: si = convert_from_path(name, int(DPI), thread_count=int(threads)) for i, si in enumerate(si): imgf = BytesIO() si.save(imgf, format='tiff') data = imgf.getvalue() imgf.seek(0) width, height = si.size presentation.slide_height = height * 9525 presentation.slide_width = width * 9525 slide = presentation.slides.add_slide( presentation.slide_layouts[6]) picture = slide.shapes.add_picture(imgf, 0, 0, width=width * 9525, height=height * 9525) presentation.save(name.replace(".pdf", "(pdf2ppt).ppt")) lblpdftopptBTN.config(text="Done!")
def create_presentation(): # Enter directory of image files here directory = "demo/" slidesDir = os.listdir(directory) prs = Presentation() # Iterates through images in the directory, creates new slide with image for slides in slidesDir: slide = prs.slides.add_slide(prs.slide_layouts[6]) fileName= directory + slides try: pic = slide.shapes.add_picture(fileName, 0, 0) except: print(slides + " is not an image file") continue # Sets size of presentation to the image prs.slide_height = pic.height prs.slide_width = pic.width # Enter output directory and name here prs.save("output.pptx")
def generatePptx(self, reference): fileName = "biblia.pptx" book_chapter = reference[0] left = top = 0 width = Inches(16) height = Inches(9) pptx = Presentation() pptx.slide_width = width pptx.slide_height = height for i in range( len(reference)): # Adicionar um slide novo para cada versículo if (i == 0): continue # Pular primeiro elemento verse = reference[i] # ## Criação do slide e definição do seu tipo, fundo preto layout = pptx.slide_layouts[6] slide = pptx.slides.add_slide(layout) background = slide.background fill = background.fill fill.solid() fill.fore_color.rgb = RGBColor(0, 0, 0) # ## Adicionar caixa de texto para referência txBox = slide.shapes.add_textbox(Inches(0.1), Inches(8.9), width, Inches(0.5)) if ":" in book_chapter else \ slide.shapes.add_textbox(Inches(0.1), Inches(8.4), width, Inches(0.5)) # left, top, width, height text_frame = txBox.text_frame text_frame.vertical_anchor = MSO_ANCHOR.BOTTOM # ## Escrever o parágrafo no slide e definir a característica do texto de referência p = text_frame.paragraphs[0] p.text = book_chapter p.font.bold = True p.font.size = Pt(30) p.font.color.rgb = RGBColor(255, 255, 255) # ## Adicionar caixa de texto para versículo txBox = slide.shapes.add_textbox( Inches(0.5), Inches(0.65), Inches(15), Inches(7.7)) # left, top, width, height text_frame = txBox.text_frame text_frame.vertical_anchor = MSO_ANCHOR.MIDDLE text_frame.word_wrap = True # ## Escrever o parágrafo no slide e definir a característica do texto de versículo p = text_frame.paragraphs[0] p.alignment = PP_ALIGN.JUSTIFY_LOW p.word_wrap = True p.text = verse p.font.size = Pt(40) p.font.bold = True p.font.color.rgb = RGBColor(255, 255, 255) pptx.save(fileName) return fileName
def pres(data, name, directory): pres = Presentation() # Set slide dimentions pres.slide_width = 6858000 pres.slide_height = 9144000 # Get title slide title_layout = pres.slide_layouts[0] # Get first slide title_slide = pres.slides.add_slide( title_layout ) title = title_slide.shapes.title title.text = name # Make each page for page in range( 0, math.ceil( len(data)/4 ) ): # Make slide page_layout = pres.slide_layouts[1] slide = pres.slides.add_slide( page_layout ) # Get shape shape = slide.shapes for order in range(0, 4): position = (page * 4) + (order) # Make sure it is in the data if not position > (len(data) - 1): # Make sure in range of data list # Get positions left = Inches(3) width = Inches(5) height = Inches(2) # Get top Position if order == 0: top_inches = 1 top_par = 1.2 else: top_inches = (order * 2) + 1 top_par = 1.2 top = Inches( top_inches ) top_paragraph = Inches( top_par ) # Create Image if 'image' in data[position]: image_path = str(directory) + '/Photos/' + str(data[position]['image']) image_left = Inches(1) pic = shape.add_picture(image_path, image_left, top) # Textbox txBox = shape.add_textbox(left, top, width, height) txBox2 = shape.add_textbox(left, top_paragraph, width, height) name = txBox.text_frame name.text = str( data[position]['first_name'] ) + ' ' + str( data[position]['last_name'] ) content = txBox2.text_frame if 'questions' in data[position]: content.text = 'University: {0} \nInterest: {1} \nFavorite Film: {2} \nDinner Invites: {3}'.format( str(data[position]['university']), str(data[position]['questions']), str(data[position]['questions']), str(data[position]['questions']) ) else: content.text = '' # Save presentation pres_name = str(name) + '.pptx' pres.save( pres_name )
from pptx import Presentation from pptx.util import Inches, Cm, Pt from fpdf import FPDF ######## # PPTX # ######## prs = Presentation('template.pptx') prs.slide_width = Cm(33.876) prs.slide_height = Cm(19.05) slide = prs.slides.add_slide(prs.slide_layouts[1]) slide.shapes.title.text = 'Test' pic = slide.shapes.add_picture('plot.png', 0, prs.slide_height / 12 * 4, width=prs.slide_width, height=prs.slide_height / 12 * 3) slide.shapes[0]._element.addprevious(pic._element) pic = slide.shapes.add_picture('plot.png', 0, prs.slide_height / 12 * 8, width=prs.slide_width, height=prs.slide_height / 12 * 3) slide.shapes[1]._element.addprevious(pic._element)
def ppt_existed(ppt_name): if not os.path.exists(ppt_name): prs = Presentation() prs.slide_height = cm_to_in(14.35) prs.slide_width = cm_to_in(25.5) prs.save(ppt_name)
def image2pptx(argv=sys.argv[1:]): """Paste images to PowerPoint. Args: --image-path (Path, optional) : Paths to image files. Defaults to ``()``. --image-dir (Path, optional) : Path to the directory where images are. Defaults to ``None``. -W/--slide-width (int, optional) : The width of PowerPoint slide. Defaults to ``9144000``. -H/--slide-height (int, optional) : The height of PowerPoint slide. Defaults to ``6858000``. --slide-size (str, optional) : The size of PowerPoint slide. Please chose from ``["4:3", "16:9"]``. Defaults to ``"4:3"``. -O/--outpptx (Path, optional) : The path to the created PowerPoint. Defaults to ``Path("test.pptx")``. Note: When you run from the command line, execute as follows:: $ image2pptx --image-path /path/to/image1.png \\ /path/to/image2.jpg \\ /path/to/image3.jpeg \\ --image_dir /path/to/image_dir \\ --slide-size "16:9" \\ --outpptx "image.pptx" """ parser = argparse.ArgumentParser(prog="image2pptx", description="Paste images to PowerPoint", add_help=True) parser.add_argument("--image-path", type=Path, nargs="*", help="Paths to image files.") parser.add_argument("--image-dir", type=Path, help="Path to the directory where images are.") parser.add_argument("-W", "--slide-width", type=int, default=9144000, help="The width of PowerPoint slide.") parser.add_argument("-H", "--slide-height", type=int, default=6858000, help="The height of PowerPoint slide.") parser.add_argument("--slide-size", type=str, default=None, choices=["4:3", "16:9"], help="The size of PowerPoint slide.") parser.add_argument("-O", "--outpptx", type=Path, default=Path("test.pptx"), help="The path to the created PowerPoint.") args = parser.parse_args() image_paths = list(args.image_path) if args.image_dir is not None: image_paths += sorted([ path for path in args.image_dir.rglob("*") if path.suffix.lower() in IMAGE_EXTENSIONS ]) slide_size = args.slide_size if slide_size is not None: slide_width, slide_height = { "4:3": (9144000, 6858000), "16:9": (12193200, 6858000), }[slide_size] else: slide_width = args.slide_width slide_height = args.slide_height prs = Presentation() prs.slide_width = slide_width prs.slide_height = slide_height blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) left = top = 0 for image_path in image_paths: img = Image.open(image_path) slide.shapes.add_picture( image_file=str(image_path), left=left, top=top, ) left += img.width * 1e4 if left >= slide_width: top += img.height * 1e4 left = 0 prs.save(file=args.outpptx)
def addImageSlide(imageFileName): """ Adds a full-screen image to a blank full-screen slide. """ slide = prs.slides.add_slide(blank_slide_layout) slide.shapes.add_picture(imageFileName, 0, 0, height=prs.slide_height, width=prs.slide_width) # Get today's date, formatted to MATLAB's default (e.g. 2017-Jul-09) today = date.today().strftime('%d-%b-%Y') # make filename reportFile = today + '_report.pptx' # Initialize presentation prs = Presentation() prs.slide_height = 5143500 # Widescreen aspect ratio title_slide_layout = prs.slide_layouts[1] blank_slide_layout = prs.slide_layouts[6] # blank slide # Create title slide addTitleSlide('Current Cycling Progress', today) # CD to directory with most recent images # os.chdir('C:\\Users\\Arbin\\Box Sync\\Batch images\\' + today + '\\') # Add .png files in this directory. Start with summary figures all_images = glob.glob('*.png') for file in all_images: if "summary" in file: addImageSlide(file)
def make_presentation(self, width, height): prs = Presentation() prs.slide_width = Inches(width) prs.slide_height = Inches(height) return prs
HEADER = "Any[" FOOTER = "]" SPLITTER = '--- SPLITTER ---' # Must same with sysmap_jl.jl def. SLIDE_TYPE = 6 # 6: Blank slide. 5: One title slide TITLE = "Technology System Map" # Only used in slide_title. print("=== sysmap_pptx: Start.") if __name__ == "__main__": prs = Presentation() #--- Default slide width prs.slide_width = 9144000 # prs.slide_height = 6858000 # 4:3 prs.slide_height = 5143500 # 16:9 #--- create one blank slide slide = prs.slides.add_slide(prs.slide_layouts[SLIDE_TYPE]) # if use the following title, set slide 5 instead of 6(blank) # in the upper code line. # title = slide.shapes.title # title.text = 'Technology System Map' # title.text = TITLE #--- Set each item to the slide fn = sys.argv[1] # input position data file. fd = open(fn, 'r') fo = sys.argv[2] # print "fn : %s" % fn
from pptx import Presentation from pptx.util import Inches from parse import parse_csv, bonus_csv from slides import fill_slide, bonus_card presentation = Presentation() presentation.slide_width = Inches(2.5) presentation.slide_height = Inches(3.5) cards = parse_csv('cards.csv') bonus = bonus_csv('bonus.csv') def add_slide_from_card(c): layout = presentation.slide_layouts[6] slide = presentation.slides.add_slide(layout) fill_slide(slide, c) def add_bonus_card(c): layout = presentation.slide_layouts[6] slide = presentation.slides.add_slide(layout) bonus_card(slide, c) for card in cards: add_slide_from_card(card) for card in bonus: add_bonus_card(card) presentation.save('cards.pptx')
# @Software: PyCharm from pathlib import Path from openpyxl import load_workbook from pptx import Presentation from pptx.util import Cm, Pt from pptx.dml.color import RGBColor from pptx.enum.text import PP_PARAGRAPH_ALIGNMENT, MSO_ANCHOR from pptx.enum.shapes import MSO_SHAPE src_folder = Path( '/Users/liupan/work/code/seal-python-tools/ppt_process/公司产品介绍/') ppt_file = Presentation() sl_w = Cm(40) sl_h = Cm(22.5) ppt_file.slide_width = sl_w ppt_file.slide_height = sl_h wb = load_workbook(src_folder / '产品信息表.xlsx') ws = wb.active for row in range(2, ws.max_row + 1): slide = ppt_file.slides.add_slide(ppt_file.slide_layouts[6]) slide.background.fill.solid() slide.background.fill.fore_color.rgb = RGBColor(230, 230, 230) rec = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, left=0, top=(sl_h - Cm(10)) // 2, width=sl_w, height=Cm(10)) rec.fill.solid() rec.fill.fore_color.rgb = RGBColor(197, 90, 17) rec.line.fill.background() pic_path = src_folder / (str(ws.cell(row=row, column=1).value) + '.png')
days_ahead = weekday - d.weekday() if days_ahead <= 0: # Target day already happened this week days_ahead += 7 return (d + datetime.timedelta(days_ahead)).strftime("%Y%m%d") #today = date.today() d = date.today() next_sunday = next_weekday(d, 6) # 0 = Monday, 1=Tuesday, 2=Wednesday... #next_sunday = today.strftime("%Y%m%d") #print(next_monday) #d4 = datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%Y%m%d") #print(next_sunday) prs = Presentation() factor = .5 prs.slide_height = Inches(11.25 * factor) prs.slide_width = Inches(20 * factor) if not os.path.exists('sonntag'): os.makedirs('sonntag') def change_permissions_recursive(path, mode): for root, dirs, files in os.walk(path, topdown=False): for dir in [os.path.join(root,d) for d in dirs]: os.chmod(dir, mode) for file in [os.path.join(root, f) for f in files]: os.chmod(file, mode) change_permissions_recursive('sonntag', 0o777) for root, dirs , filenames in os.walk("./{0}/".format(next_sunday)): valid_images = [".jpg",".png"] for file in sorted(filenames):
#! /usr/bin/env python import csv, sys, numpy, math, pandas, os from pptx import Presentation from pptx.util import Inches, Pt from pptx.enum.text import PP_ALIGN from pptx.dml.color import RGBColor from pptx.enum.dml import MSO_THEME_COLOR from pathlib import Path prs = Presentation() prs.slide_height = Inches(5.63) prs.slide_width = Inches(10) blank_slide_layout = prs.slide_layouts[6] width = Inches(10) #(left, top, width, height) textfile1 = open(sys.argv[1]).read().splitlines() textfile2 = open(sys.argv[2]).read().splitlines() count = 0 count1 = 0 for line in textfile1: slide = prs.slides.add_slide(blank_slide_layout) #print("go") txBox = slide.shapes.add_textbox(Inches(0), Inches(3.36), width, Inches(0.64)) tf = txBox.text_frame p = tf.paragraphs[0] p.alignment = PP_ALIGN.CENTER run = p.add_run()
'methCpG_meta': 'methCpG_metaplot', 'weblogo': 'WebLogo', 'rna_folding': 'RNA Folding Free Energy' } for measure_type in measure_type_dict[measure_branch]: pptx_name = out_dir + '/pptx_' + measure_branch + '_multiAnal_' if measure_branch == 'coverage': pptx_name = pptx_name + measure_type + '_' pass pptx_name = pptx_name + suf ## initialize pptx prs = Presentation() prs.slide_width = Inches(11.69) prs.slide_height = Inches(10.27) # prs.slide_width = Inches( 11.69 ) # prs.slide_height = Inches( 8.27 ) slide_marge_left = Inches(0.39) slide_marge_right = slide_marge_left slide_marge_top = slide_marge_left + Inches(0.1) slide_marge_bottom = slide_marge_left height_tbx = Inches(0.3) img_height = Inches(3.5) #2.45 font_size_big = Pt(24) #16 font_size_small = Pt(12) ## pages #########
def combine_rows(self, data: List[Component], bounds: Bounds): # We load a template from a file to have some nicer line styles etc by default # (they cannot currently be specified via python-pptx) with tempfile.TemporaryDirectory() as tmpdir: themedata = pkg_resources.read_binary(__package__, "theme.pptx") p = os.path.join(tmpdir, "theme.pptx") with open(p, "wb") as f: f.write(themedata) prs = Presentation(p) # Create a single slide presentation with a blank slide # prs = Presentation() prs.slide_height = Mm(bounds.height) prs.slide_width = Mm(bounds.width) blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) # Add all our elements to the slide flat = [] for row in data: flat.extend(row) # Generate all images in parallel futures = [] for c in flat: if isinstance(c, ImageComponent): futures.append( self._thread_pool.submit(self._add_image, c, slide)) for f in futures: f.result() # Add everything else afterwards, to ensure proper z-order for c in flat: if isinstance(c, TextComponent): if c.rotation == 90.0 or c.rotation == -90.0: # The shape is rotated about its center. We want a rotation about the top left corner instead. # Since we only allow 90° rotations, we can correct for that with a simple translation pos_top = c.bounds.top + c.bounds.height / 2. - c.bounds.width / 2. pos_left = c.bounds.left - c.bounds.height / 2. + c.bounds.width / 2. # swap height and width height, width = c.bounds.width, c.bounds.height shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Mm(pos_left), Mm(pos_top), Mm(width), Mm(height)) # tikz rotation is counter-clockwise, pptx clockwise (we switch in pptx) shape.rotation = -c.rotation else: shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Mm(c.bounds.left), Mm(c.bounds.top), Mm(c.bounds.width), Mm(c.bounds.height)) shape.shadow.inherit = False # Background color if c.background_color is not None: shape.fill.solid() shape.fill.fore_color.rgb = RGBColor( c.background_color[0], c.background_color[1], c.background_color[2]) else: shape.fill.background() shape.line.fill.background() # Text properties text_frame = shape.text_frame p = text_frame.paragraphs[0] p.alignment = { "center": PP_ALIGN.CENTER, "left": PP_ALIGN.LEFT, "right": PP_ALIGN.RIGHT }[c.horizontal_alignment] text_frame.margin_top = 0 text_frame.margin_bottom = 0 if c.horizontal_alignment == 'right': text_frame.margin_right = Mm(c.padding.width_mm) text_frame.margin_left = 0 else: text_frame.margin_right = 0 text_frame.margin_left = Mm(c.padding.width_mm) run = p.add_run() run.text = c.content.replace("\\\\", "\n") run.font.color.rgb = RGBColor(c.color[0], c.color[1], c.color[2]) run.font.size = Pt(c.fontsize) if isinstance(c, RectangleComponent): shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Mm(c.bounds.left), Mm(c.bounds.top), Mm(c.bounds.width), Mm(c.bounds.height)) shape.shadow.inherit = False shape.line.color.rgb = RGBColor(c.color[0], c.color[1], c.color[2]) shape.line.width = Pt(c.linewidth) # shape.line.join_type = 'Miter' # Removes rounded edges, but is not supported, yet (sadly) shape.fill.background() if isinstance(c, LineComponent): shape = slide.shapes.add_connector(MSO_CONNECTOR.STRAIGHT, Mm(c.from_x), Mm(c.from_y), Mm(c.to_x), Mm(c.to_y)) shape.shadow.inherit = False shape.line.color.rgb = RGBColor(c.color[0], c.color[1], c.color[2]) shape.line.width = Pt(c.linewidth) return prs
def append_slide_to_presentation(ppt_fpath, distribution_fpath, topo_fpath, movie_fpath, subject, info_dict=None): """ Append a slide to an existing presentation. This function is just an example where images for a distribution, topographical (static) map, topographical (moving) map and basic info are added to a ppt slide. The ppt must already exist for this function to work. See `create_title_slide`. Parameters ---------- ppt_fpath: pathlib.Path Absolute path of location to save the ppt. Must be the same as used in create the presentation. distribution_fpath: pathlib.Path Absolute path of the distribution plot. Can be any image format. topo_fpath: pathlib.Path Absolute path of the topographical map. Can be any image format movie_fpath: pathlib.Path Absolute path of the topographical movie. Only tested with mp4 so far subject: str Name of the subject to include on the slide info_dict: dict Dict of extra information about the subject/run you would like to include on the slide. Returns ------- """ # Open the existing presentation prs = Presentation(ppt_fpath) prs.slide_width = Inches(16) prs.slide_height = Inches(9) # Append a new blank slide blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) # Add distribution plot. Mess around with the size and position parameters on a single slide before automating this # in a loop left = Inches(10.5) top = Inches(0) width = Inches(5) distribution_img = slide.shapes.add_picture(str(distribution_fpath), left, top, width=width) # Add the topomap left = Inches(1.5) top = Inches(1.5) width = Inches(9) topomap_img = slide.shapes.add_picture(str(topo_fpath), left, top, width=width) # Add the text box that contains subject information. You will have to adjust the width and height parameters # depending on how much info you want to include in the slide left = top = Inches(0) width = Inches(2.2) height = Inches(1) metadata = slide.shapes.add_textbox(left, top, width, height) tf = metadata.text_frame subject_txt = tf.add_paragraph() subject_txt.text = f"Subject: {subject}" subject_txt.font.size = Pt(16) for key, value in info_dict.items(): info_txt = tf.add_paragraph() info_txt.text = f"{key}: {value}" info_txt.font.size = Pt(16) # Add a movie on its own slide if movie_fpath: left = Inches(4) width = Inches(9) movie_slide = prs.slides.add_slide(blank_slide_layout) movie_slide.shapes.add_movie(movie_fpath, left, top, width=width, height=width) prs.save(ppt_fpath)
def generate_deck(self, playlist_name): playlist_filepath = os.path.join(self.settings.playlist_path, playlist_name + '.m3u') if not os.path.isfile(playlist_filepath): print('Playlist not found') return None #deal with logo with open(playlist_filepath, "r", encoding='utf-8') as f: content = f.readlines() music_filepaths = [x.strip() for x in content] logo_path = os.path.join(self.settings.playlist_path, playlist_name + '.png') if not os.path.isfile(logo_path): logo_path = os.path.join(self.default_wd, 'ForgedCards/template/logo.png') prs = Presentation() prs.slide_width = Cm(6) prs.slide_height = Cm(9) blank_slide_layout = prs.slide_layouts[6] for controller, qr_text in self.CONTROLLER: front_controller_slide = prs.slides.add_slide(blank_slide_layout) self.add_album_cover_info(front_controller_slide, controller, '') front_controller_slide.shapes.add_picture( os.path.join(self.default_wd, 'ForgedCards/controller/' + controller + '.png'), Cm(2.6), Cm(6.9), Cm(0.8), Cm(0.8)) self.add_front_bottom_right(front_controller_slide, playlist_name, None, music_filepaths, logo_path) self.add_bottomleft(front_controller_slide, qr_text) qr_code = qrcode.make(qr_text) qr_code.save( os.path.join(self.default_wd, 'ForgedCards/tmp/qr_code.png')) back_controller_slide = prs.slides.add_slide(blank_slide_layout) self.add_QR_code(back_controller_slide) self.add_ribbon(back_controller_slide) self.add_SAMsJukebox(back_controller_slide) self.add_MusicInYourHand(back_controller_slide) # FRONT SLIDE front_slide_playlist = prs.slides.add_slide(blank_slide_layout) self.add_album_cover_info(front_slide_playlist, playlist_name, 'Playlist') # bottom left self.add_bottomleft(front_slide_playlist, '') # bottom right self.add_front_bottom_right(front_slide_playlist, playlist_name, 0, music_filepaths, logo_path) self.add_genre(front_slide_playlist, 'Playlist') # QR Code Side qr_slide = prs.slides.add_slide(blank_slide_layout) qr_code = qrcode.make(playlist_name + '.m3u') qr_code.save( os.path.join(self.default_wd, 'ForgedCards/tmp/qr_code.png')) self.add_QR_code(qr_slide) self.add_ribbon(qr_slide) self.add_SAMsJukebox(qr_slide) self.add_MusicInYourHand(qr_slide) n = 0 for music_file in music_filepaths: if music_file.endswith(".mp3") and music_file.startswith('../'): music_file = music_file[3:] print(music_file) songpath = self.settings.library_path + '/' + music_file n = n + 1 song_info = MP3(songpath, ID3=EasyID3) albumartist = song_info['albumartist'][0] tracknumber = song_info['tracknumber'][0] song_date = song_info['date'][0] song_title = song_info['title'][0] song_genre = song_info['genre'][0] qr_code = qrcode.make(music_file) qr_code.save( os.path.join(self.default_wd, 'ForgedCards/tmp/qr_code.png')) tags = ID3(songpath) pict = tags.get("APIC:").data im = Image.open(BytesIO(pict)) im.save( os.path.join(self.default_wd, 'ForgedCards/tmp/album_cover.png')) # FRONT SLIDE front_slide = prs.slides.add_slide(blank_slide_layout) self.add_album_cover_info(front_slide, albumartist, song_title) # bottom left self.add_bottomleft(front_slide, tracknumber + ' ' + song_date) # bottom right self.add_front_bottom_right(front_slide, playlist_name, n, music_filepaths, logo_path) self.add_genre(front_slide, song_genre) # QR Code Side qr_slide = prs.slides.add_slide(blank_slide_layout) self.add_QR_code(qr_slide) self.add_ribbon(qr_slide) self.add_SAMsJukebox(qr_slide) self.add_MusicInYourHand(qr_slide) prs.save( os.path.join(self.settings.playlist_path, playlist_name + '.pptx'))
def makeppt(data): prs = Presentation() prs.slide_width = Inches(16) prs.slide_height = Inches(9) title = titles[data] text = songs[data] text = text.split('\n\n') text.pop(0) text = list(filter(None, text)) originallen = len(text) chorus = None for i in range(originallen): stanza = text[i] if stanza.startswith("Chorus:") or stanza.startswith("Refrain:"): chorus = i break if chorus: i = chorus + 2 while True: text.insert(i, stanza) i += 2 if i > len(text): break blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) txBox = slide.shapes.add_textbox(0, 0, Inches(16), Inches(9)) tf = txBox.text_frame tf.vertical_anchor = MSO_ANCHOR.MIDDLE p = tf.add_paragraph() p.text = title + '\n(' + data + ')' p.font.size = Pt(60) p.font.bold = True p.alignment = PP_ALIGN.CENTER for i in range(len(text)): blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) txBox = slide.shapes.add_textbox(Inches(15), 0, Inches(1), Inches(1)) tf = txBox.text_frame p = tf.add_paragraph() p.text = '{}/{}'.format(i + 1, len(text)) p.font.size = Pt(32) txBox = slide.shapes.add_textbox(0, 0, Inches(16), Inches(9)) tf = txBox.text_frame tf.vertical_anchor = MSO_ANCHOR.MIDDLE tf.word_wrap = True tf.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT p = tf.add_paragraph() p.text = text[i] p.font.size = Pt(48) p.font.bold = True p.alignment = PP_ALIGN.CENTER pptxfile = BytesIO() pptxfile.name = data + '.pptx' prs.save(pptxfile) pptxfile.seek(0) return pptxfile
hymns.append(current_hymn) # See if any extracfted hymns are empty for j in range(len(hymns)): if len(hymns[j]) == 0: print(pptx_file_names[j], "Length: 0") # Start creating powerpoints for all of the extracted hymns for h in range(len(hymns)): prs = Presentation() blank_slide_layout = prs.slide_layouts[6] if aspect_ratio.lower() == 'wide': # 16:9 Aspect ratio prs.slide_height = 6858000 prs.slide_width = 12192000 else: # 4:3 Aspect ration prs.slide_height = 6858000 prs.slide_width = 9144000 # Create Title Slide title_slide = prs.slides.add_slide(blank_slide_layout) # Add picture pic = title_slide.shapes.add_picture(images_path[h % len(images_path)], 0, 0) pic.height = prs.slide_height pic.width = prs.slide_width
names, codes, urls, images_urls = get_leihlokaldata() if not os.path.isdir('products'): os.makedirs('products') # now download the images, store them. # poor webserver, we download everything in batches of 100. should be quite fast. images = Parallel(n_jobs=8, prefer='threads')( delayed(download_image)(url, code) for url, code in tqdm(list(zip(images_urls, codes)))) products_mapping = {code:name for code, name in zip(codes, names)} # approximately the display size width = Cm(33) height = Cm(20) prs = Presentation() prs.slide_width = width prs.slide_height = height for code in tqdm(codes, desc='writing pptx'): try: # for all items: create a slide. make_slide(code) except: print("failed to create slide for item " + str(code)) prs.save('raspberry-pi-fenster.pptx') # now open it os.startfile( os.path.abspath('raspberry-pi-fenster.pptx'))
def generatePptx(self, title, author, lyrics): left = top = 0 width = Inches(16) height = Inches(9) pptx = Presentation() pptx.slide_width = width pptx.slide_height = height fileName = title + " - " + author + ".pptx" # ## Criar um slide incial para o título e autor/banda, e definir seu tipo de slide para 6 (vazio) layout = pptx.slide_layouts[6] slide = pptx.slides.add_slide(layout) # ## Adicionar forma preta no fundo shapes = slide.shapes shape = shapes.add_shape( MSO_SHAPE.RECTANGLE, left, top, width, height ) # ## Adicionar transparência à forma fill = shape.fill fill.solid() fill.fore_color.rgb = RGBColor(0, 0, 0) self._set_shape_transparency(shape, 50000) line = shape.line line.fill.background() # ## Adicionar caixa de texto txBox = slide.shapes.add_textbox(left, top, width, height) tf = txBox.text_frame tf.vertical_anchor = MSO_ANCHOR.MIDDLE tf.word_wrap = True # ## Escrever o título da música e definir as características do seu texto p = tf.paragraphs[0] p.text = title # self._set_p_border(p) p.font.bold = True p.font.size = Pt(80) p.alignment = PP_ALIGN.CENTER p.font.color.rgb = RGBColor(255,255,255) # ## Escrever o autor/banda da música e definir as características do seu texto p = tf.add_paragraph() p.text = author p.font.bold = True p.font.italic = True p.font.size = Pt(50) p.alignment = PP_ALIGN.CENTER p.word_wrap = True p.font.color.rgb = RGBColor(255,255,255) for i in range(len(lyrics)): # Adicionar um slide novo para cada parágrafo da letra da música # ## Criação do slide e definição do seu tipo layout = pptx.slide_layouts[6] slide = pptx.slides.add_slide(layout) # ## Criação de uma forma para o fundo shapes = slide.shapes shape = shapes.add_shape( MSO_SHAPE.RECTANGLE, left, top, width, height ) # ## Adicionar transparência à forma fill = shape.fill fill.solid() fill.fore_color.rgb = RGBColor(0, 0, 0) self._set_shape_transparency(shape, 50000) line = shape.line line.fill.background() # ## Adicionar caixa de texto txBox = slide.shapes.add_textbox(left, top, width, height) tf = txBox.text_frame tf.vertical_anchor = MSO_ANCHOR.MIDDLE tf.word_wrap = True # ## Escrever o parágrafo no slide e definir a característica do texto p = tf.paragraphs[0] p.alignment = PP_ALIGN.CENTER p.word_wrap = True p.text = lyrics[i].replace('\n\n', '') p.font.bold = True p.font.size = Pt(60) p.font.color.rgb = RGBColor(255,255,255) pptx.save(fileName) return fileName
print("...complete.") print() # Loop over slides for i, slideimg in enumerate(slideimgs): if i % 10 == 0: print("Saving slide: " + str(i)) imagefile = BytesIO() slideimg.save(imagefile, format='tiff') imagedata = imagefile.getvalue() imagefile.seek(0) width, height = slideimg.size # 调整幻灯片大小 prs.slide_height = height * 9525 prs.slide_width = width * 9525 # Add slide slide = prs.slides.add_slide(blank_slide_layout) pic = slide.shapes.add_picture(imagefile, 0, 0, width=width * 9525, height=height * 9525) # Save Powerpoint print() print("Saving file: " + base_name + ".pptx") prs.save(base_name + '.pptx') print("Conversion complete. :)")