How to remove the blank text boxes from python pptx generated slides? - python

from pptx import Presentation
from pptx.util import Inches
prs = Presentation("my_pptfile_begin.pptx")
left = Inches(0.6)
top = Inches(1.7)
blank_slide_1 = prs.slide_layouts[6]
add_the_slide = prs.slides.add_slide(blank_slide_1)
img_path1 = 'Three_Part_Set_Difference_excel_printout.png'
slide1=prs.slides[1]
pic = slide1.shapes.add_picture(img_path1, left, top)
blank_slide_2 = prs.slide_layouts[6]
add_the_slide = prs.slides.add_slide(blank_slide_2)
img_path2 = 'my_image.png'
slide2=prs.slides[2]
pic = slide2.shapes.add_picture(img_path2, left, top)
logoleft = Inches(4.7)
logotop = Inches(1.8)
blank_slide_3 = prs.slide_layouts[6]
add_the_slide = prs.slides.add_slide(blank_slide_3)
img_path3 = 'logo_slide.png'
slide3=prs.slides[3]
pic = slide3.shapes.add_picture(img_path3, logoleft, logotop)
prs.save('my_pptfile_Final.pptx')
How to remove the blank text boxes (or as a matter of fact all textboxes)?
I do not need any text boxes in my Powerpoint output file

If you're talking about empty placeholder shapes, just use a slide layout that has no placeholders.
In the default template used when you call Presentation() by itself (without an argument), that is the seventh layout I believe (prs.slide_layouts[6]).
But you need to adjust that for whatever starting .pptx file you're using ("my_pptfile_begin.pptx" in your case) by looking at it in slide-master view and counting down to the blank layout (or adding one if it doesn't have one).

blank_slide_3 = prs.slide_layouts[x] where x the slide number of the default template of your pptx application or your company's default template.
Therefore you need to know the default template and know the blank slide with no textboxes of that template based on the defaults of your ppt application

Related

Insert blank slide with python-pptx in existing presentation

I'm working with the python-pptx library and I'm trying to insert a blank slide at a specific place (slide with the same dimensions).
I know how to delete a slide :
def delete_slides(presentation, index):
xml_slides = presentation.slides._sldIdLst
slides = list(xml_slides)
xml_slides.remove(slides[index])
But how to insert a blank slide?
Someone will probably come along with a better solution but you could just create a blank slide and then move it to the location you want.
from pptx import Presentation
def move_slide(old_index, new_index):
xml_slides = presentation.slides._sldIdLst
slides = list(xml_slides)
xml_slides.remove(slides[old_index])
xml_slides.insert(new_index, slides[old_index])
presentation = Presentation("test1.pptx")
layout = presentation.slide_masters[0].slide_layouts[6]
slide = presentation.slides.add_slide(layout)
slide_id = presentation.slides.index(slide)
move_slide(slide_id, 5)
presentation.save("test1.pptx")

Reportlab alignment & width issues

I’m having some issues with reportlab and writing a PDF. When the PDF is written it only consumes a little less than 2/3 of the page width (letter). The heading, for example, wraps and never makes it past the halfway point of the document.
I’m at a loss for how to get my tables and paragraph to use the full width of the page.
Any insight is greatly appreciated.
Thank you in advance.
import io
import os
from django.core.files.base import ContentFile
from jsignature.utils import draw_signature
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_RIGHT, TA_CENTER, TA_LEFT
from reportlab.lib.units import inch
from reportlab.pdfgen import canvas
from reportlab.platypus import SimpleDocTemplate, Paragraph, Table
from PIL import Image
# create pdf with table and paragraphs
def create_pdf(participant):
# create a file-like buffer to receive PDF data
buffer = io.BytesIO()
# define styles
styles = getSampleStyleSheet()
style_general = ParagraphStyle(
name='left',
parent=styles['Normal'],
fontSize=12,
fontName='Helvetica',
alignment=TA_LEFT)
style_image = ParagraphStyle(
name='left',
fontSize=30,
parent=styles['Normal'],
alignment=TA_LEFT)
style_heading = ParagraphStyle(
name='center',
fontSize=18,
fontName='Helvetica-Bold',
parent=styles['Heading1'],
leading=18,
alignment=TA_CENTER)
# create a simple document with page size in buffer
doc = SimpleDocTemplate(buffer, pagesize=letter, author='Me')
# create a list of paragraphs
AllParagraphs = []
# convert png image to jpeg
jpeg_image = get_jpeg_image(participant)
# add rows and columns so that the data can align
table_data = [
[Paragraph("My Heading - It should span the full page width", style_heading)],
[
Paragraph('Name:', style_general),
Paragraph(
f'{participant.first_name} {participant.middle_initial} {participant.last_name}',
style_general)
],
[
Paragraph(f'Signature:', style_general),
# image height of 30 to prevent overlapping since fontSize is 30,
# image width of double to maintain aspect ratio
Paragraph(
"<img src='{0}' valign='middle' width=60 height=30 />".format(
jpeg_image),
style_image)
]
]
# set rows and columns into Table object
table_element = Table(table_data)
# add table to list of paragraphs
AllParagraphs.append(table_element)
# build document with list of paragraphs
doc.build(AllParagraphs)
# get content of buffer
buffer.seek(0)
pdf_data = buffer.getvalue()
# save buffer content to django File object
file_data = ContentFile(pdf_data)
# name pdf file
file_data.name = f'{participant.last_name}.pdf'
# delete jpeg file
os.remove(jpeg_image)
# save pdf file to parent model
participant.pdf = file_data
participant.save()
For those interested in the answer: adjusting the table style to span multiple columns was the right approach.
In this case a table is being used to best align the signature elements, so spanning the columns similar to how you would in html or css is the solution.
...
# existing code for placement reference
# set rows and columns into Table object
table_element = Table(table_data)
# add table to list of paragraphs
# new code for spanning
# style table object to make single cells span both columns
table_element.setStyle(TableStyle([
('SPAN', (0, 0), (1, 0)),
]))

Python-pptx Import Slide Layout

I'm working with pptx to create templates based on info in existing slides. I can create a slide, define its layout, enter text, etc. I can do all the basics. I want to create a slide in a new ppt based on an input ppt and use the same amount of slides as the original, all with their original layouts, and just change some text. How can I access a specific slide's layout # without knowing beforehand? All the other answers say "new_slide_layout = prs.slides.slide_layouts[i]" where i is a number they have defined in the code (usually 0). I'm trying to get that i from the input file and use it without choosing slide type as a user. How can I do this?
Latest functional code:
inputf = pptx.Presentation(input_file)
prs = pptx.Presentation()
old_slide_list = []
slides = inputf.slides
slide_count = 0
for slide in slides:
old_slide_list.append(slide)
slide_count += 1
old_text_runs = []
new_text_runs = []
for i in range(0, slide_count):
old_slide = old_slide_list[i]
old_runs_count = 0
nl = int(input("Enter your choice for this slide's layout (0-8):"))
new_layout = prs.slide_layouts[nl]
new_slide = prs.slides.add_slide(new_layout)
I can allow the user to choose their own slide layout but if I try to rip it directly from the old slide and use it for the new slide it damages the new ppt and it will ask you to repair each time you open it. Older code that damages the presentation:
import copy
for slide in slides:
print('slide number %d' % slides.index(slide))
count += 1
tempct = 0
prs2 = pptx.Presentation()
while tempct != count:
template = prs.slides[tempct]
template_layout = template.slide_layout
new_slide = prs2.slides.add_slide(template_layout)
for shp in template.shapes:
el = shp.element
newel = copy.deepcopy(el)
new_slide.shapes._spTree.insert_element_before(newel, 'p:extLst')
tempct += 1
prs2.save(output_file)

ipywidgets: button.on_click() has output delay

Introduction
I am trying to make a small tool for classifying images using the ipywidgets in a Jupyter Notebook, but I am having some trouble aligning the classes and the images. Do you have any suggestion how to fix this.
What I did
import ipywidgets as widgets
from IPython.display import display
import glob
# My images
image_paths = glob.glob("./images/*.png")
# Display image
def display_image(path):
file = open(path, "rb")
image = file.read()
return widgets.Image(
value=image,
format='png',
width=700,
height=700,
)
# Dropdown
def create_dropdown():
return widgets.Dropdown(
options=["1","2","3","4","5","6","7","8","9","10"],
value='5',
description='Category:',
disabled=False
)
# Creating widgets
input_dropdown = create_dropdown()
button = widgets.Button(description="Submit")
output_image = widgets.Image()
output_image.value = display_image(image_paths[-1]).value
# Define function to bind value of the input to the output variable
def bind_input_to_output(sender):
image_path = image_paths[-1]
image_score = input_dropdown.value
next_image_path = image_paths.pop()
print(image_score, image_path)
output_image.value = display_image(next_image_path).value
# Tell the text input widget to call bind_input_to_output() on submit
button.on_click(bind_input_to_output)
# Displaying widgets
display(output_image, input_dropdown, button)
Results
With the above code I end up categorising the upcoming picture, but I really don't understand why. It seems the widgets does not update the image the first time I press the button.
def bind_input_to_output(sender):
image_path = image_paths.pop()
image_score = input_dropdown.value
next_image_path = image_paths[-1]
print(image_score, image_path)
output_image.value = display_image(next_image_path).value
pop first and give next filename at last item

Generating consecutive bitmaps with wxPython trouble

Well, while I don't consider myself an experienced programmer, especially when it comes to multimedia applications, I had to do this image viewer sort of a program that displays images fullscreen, and the images change when the users press <- or -> arrows.
The general idea was to make a listbox where all the images contained in a certain folder (imgs) are shown, and when someone does double click or hits RETURN a new, fullscreen frame is generated containing, at first, the image selected in the listbox but after the user hits the arrows the images change in conecutive order, just like in a regular image viewer.
At the beginning, when the first 15 - 20 images are generated, everything goes well, after that, although the program still works an intermediary, very unpleasant and highly unwanted, effect appears between image generations, where basically some images that got generated previously are displayed quickly on the screen and after this the right, consecutive image appears. On the first apparitions the effect is barelly noticeble, but after a while it takes longer and longer between generations.
Here's the code that runs when someone does double click on a listbox entry:
def lbclick(self, eve):
frm = wx.Frame(None, -1, '')
frm.ShowFullScreen(True)
self.sel = self.lstb.GetSelection() # getting the selection from the listbox
def pressk(eve):
keys = eve.GetKeyCode()
if keys == wx.WXK_LEFT:
self.sel = self.sel - 1
if self.sel < 0:
self.sel = len(self.chk) - 1
imgs() # invocking the function made for displaying fullscreen images when left arrow key is pressed
elif keys == wx.WXK_RIGHT:
self.sel = self.sel + 1
if self.sel > len(self.chk) - 1:
self.sel = 0
imgs() # doing the same for the right arrow
elif keys == wx.WXK_ESCAPE:
frm.Destroy()
eve.Skip()
frm.Bind(wx.EVT_CHAR_HOOK, pressk)
def imgs(): # building the function
imgsl = self.chk[self.sel]
itm = wx.Image(str('imgs/{0}'.format(imgsl)), wx.BITMAP_TYPE_JPEG).ConvertToBitmap() # obtaining the name of the image stored in the list self.chk
mar = itm.Size # Because not all images are landscaped I had to figure a method to rescale them after height dimension, which is common to all images
frsz = frm.GetSize()
marx = float(mar[0])
mary = float(mar[1])
val = frsz[1] / mary
vsize = int(mary * val)
hsize = int(marx * val)
panl = wx.Panel(frm, -1, size = (hsize, vsize), pos = (frsz[0] / 2 - hsize / 2, 0)) # making a panel container
panl.SetBackgroundColour('#000000')
imag = wx.Image(str('imgs/{0}'.format(imgsl)), wx.BITMAP_TYPE_JPEG).Scale(hsize, vsize, quality = wx.IMAGE_QUALITY_NORMAL).ConvertToBitmap()
def destr(eve): # unprofessionaly trying to destroy the panel container when a new image is generated hopeing the unvanted effect, with previous generated images will disappear. But it doesn't.
keycd = eve.GetKeyCode()
if keycd == wx.WXK_LEFT or keycd == wx.WXK_RIGHT:
try:
panl.Destroy()
except:
pass
eve.Skip()
panl.Bind(wx.EVT_CHAR_HOOK, destr) # the end of my futile tries
if vsize > hsize: # if the image is portrait instead of landscaped I have to put a black image as a container, otherwise in the background the previous image will remain, even if I use Refresh() on the container (the black bitmap named fundal)
intermed = wx.Image('./res/null.jpg', wx.BITMAP_TYPE_JPEG).Scale(frsz[0], frsz[1]).ConvertToBitmap()
fundal = wx.StaticBitmap(frm, 101, intermed)
stimag = wx.StaticBitmap(fundal, -1, imag, size = (hsize, vsize), pos = (frsz[0] / 2 - hsize / 2, 0))
fundal.Refresh()
stimag.SetToolTip(wx.ToolTip('Esc = exits fullscreen\n<- -> arrows = quick navigation'))
def destr(eve): # the same lame attempt to destroy the container in the portarit images situation
keycd = eve.GetKeyCode()
if keycd == wx.WXK_LEFT or keycd == wx.WXK_RIGHT:
try:
fundal.Destroy()
except:
pass
eve.Skip()
frm.Bind(wx.EVT_CHAR_HOOK, destr)
else: # the case when the images are landscape
stimag = wx.StaticBitmap(panl, -1, imag)
stimag.Refresh()
stimag.SetToolTip(wx.ToolTip('Esc = exits fullscreen\n<- -> arrows = quick navigation'))
imgs() # invocking the function imgs for the situation when someone does double click
frm.Center()
frm.Show(True)
Thanks for any advice in advance.
Added later:
The catch is I'm trying to do an autorun presentation for a DVD with lots of images on it. Anyway it's not necessarely to make the above piece of code work properly if there are any other options. I've already tried to use windows image viewer, but strangely enough it doesn't recognizes relative paths and when I do this
path = os.getcwd() # getting the path of the current working directory
sel = listbox.GetSelection() # geting the value of the current selection from the list box
imgname = memlist[sel] # retrieving the name of the images stored in a list, using the listbox selection, that uses as choices the same list
os.popen(str('rundll32.exe C:\WINDOWS\System32\shimgvw.dll,ImageView_Fullscreen {0}/imgsdir/{1}'.format(path, imgname))) # oepning the images up with bloody windows image viewer
it opens the images only when my program is on the hard disk, if it's on a CD / image drive it doesn't do anything.
There's an image viewer included with the wxPython demo package. I also wrote a really simple one here. Either one should help you in your journey. I suspect that you're not reusing your panels/frames and instead you're seeing old ones that were never properly destroyed.

Categories