本文主要是介绍Python ppt,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
python生成ppt,数据源为html
from lxml import html
from pptx import Presentation
from pptx.util import Inches
from pptx.dml.color import RGBColor
from pptx.enum.shapes import MSO_SHAPE# HTML代码
html_content = """
<html><body><div style="background-color: red; position: absolute; left: 50px; top: 200px; width: 100px; height: 20px;">Red Box</div><div style="background-color: blue; position: absolute; left: 50px; top: 250px; width: 150px; height: 20px;">Blue Box</div><div style="background-color: green; position: absolute; left: 50px; top: 300px; width: 200px; height: 20px;">Green Box</div></body>
</html>
"""# 将HTML转化为XML结构
html_tree = html.fromstring(html_content)# 设置不同颜色的RGB颜色
color_map = {'red': RGBColor(255, 0, 0),'blue': RGBColor(0, 0, 255),'green': RGBColor(0, 255, 0),'white': RGBColor(255, 255, 255)
}# 初始化PowerPoint演示文稿
prs = Presentation()# 第一页幻灯片添加标题和副标题
title_slide_layout = prs.slide_layouts[0]
title_slide = prs.slides.add_slide(title_slide_layout)
title_slide.shapes.title.text = "测试标题"
title_slide.placeholders[1].text = "测试副标题"# 第二页幻灯片(prs.slide_layouts[5]:空白布局)添加标题
blank_slide_layout = prs.slide_layouts[5]
blank_slide = prs.slides.add_slide(blank_slide_layout)
blank_slide.shapes.title.text = "HTML转化成PowerPoint例子"# 获取样式方法
def parse_style(style):styles = {}for item in style.split(';'):if ':' in item:key, value = item.split(':')styles[key.strip()] = value.strip()return styles# 转换CSS像素到PowerPoint英寸方法
def px_to_inches(px):return px / 96 # Assuming 96 pixels per inch# 循环HTML中的div元素
for div in html_tree.xpath('//div'):style = div.attrib.get('style', '')styles = parse_style(style)# 提取样式,如果没有设置背景色,则默认为白色bg_color = styles.get('background-color', 'white')width = int(styles.get('width', '100px').replace('px', ''))height = int(styles.get('height', '100px').replace('px', ''))left = int(styles.get('left', '0px').replace('px', ''))top = int(styles.get('top', '0px').replace('px', ''))# 将CSS像素到PowerPoint英寸width_in_inches = Inches(px_to_inches(width))height_in_inches = Inches(px_to_inches(height))left_in_inches = Inches(px_to_inches(left))top_in_inches = Inches(px_to_inches(top))# 获取填充颜色fill_color = color_map.get(bg_color.lower(), RGBColor(255, 255, 255))# 将形状添加到幻灯片中shape = blank_slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, # 枚举left=left_in_inches,top=top_in_inches,width=width_in_inches,height=height_in_inches,)# 设置形状的填充颜色shape.fill.solid()shape.fill.fore_color.rgb = fill_color# 保存演示文稿
prs.save('output.pptx')
print("PowerPoint file 'output.pptx' has been created.")
效果图
这篇关于Python ppt的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!