使用python和python-pptx创建ppt
在这篇博客中,我们将探讨如何使用python库`python-pptx`来创建一个简单的powerpoint演示文稿(ppt)。这个库允许我们以编程方式创建幻灯片、添加文本、图片、表格和自定义形状。
安装`python-pptx`
首先,确保你已经安装了`python-pptx`库。如果还没有安装,可以通过以下命令进行安装:
//bash pip install python-pptx
创建ppt文档
创建一个新的ppt文档非常简单:
from pptx import presentation prs = presentation()
添加标题幻灯片
我们可以添加一个包含标题和副标题的幻灯片:
slide = prs.slides.add_slide(prs.slide_layouts[0]) title = slide.shapes.title subtitle = slide.placeholders[1] title.text = "hello, world!" subtitle.text = "python-pptx was here!"
添加带有子弹点的幻灯片
接下来,我们添加一个带有子弹点的幻灯片:
slide = prs.slides.add_slide(prs.slide_layouts[1]) title_shape = slide.shapes.title body_shape = slide.placeholders[1] title_shape.text = 'adding a bullet slide' tf = body_shape.text_frame tf.text = 'find the bullet slide layout' p = tf.add_paragraph() p.text = 'use _textframe.text for first bullet' p.level = 1 p = tf.add_paragraph() p.text = 'use _textframe.add_paragraph() for subsequent bullets' p.level = 2
添加文本框
我们还可以添加一个包含多个段落的文本框:
slide = prs.slides.add_slide(prs.slide_layouts[6]) txbox = slide.shapes.add_textbox(inches(1), inches(1), inches(5), inches(1)) tf = txbox.text_frame tf.text = "this is text inside a textbox" p = tf.add_paragraph() p.text = "this is a second paragraph that's bold" p.font.bold = true p = tf.add_paragraph() p.text = "this is a third paragraph that's big" p.font.size = pt(40)
添加图片
向幻灯片中添加图片也很简单:
img_path = '1.png' slide = prs.slides.add_slide(prs.slide_layouts[6]) slide.shapes.add_picture(img_path, inches(1), inches(1)) slide.shapes.add_picture(img_path, inches(5), inches(1), height=inches(5.5))
添加自定义形状
我们可以添加自定义形状来表示流程或步骤:
slide = prs.slides.add_slide(prs.slide_layouts[5]) shapes = slide.shapes shapes.title.text = 'adding an autoshape' left = inches(0.93) top = inches(3.0) width = inches(1.75) height = inches(1.0) shape = shapes.add_shape(mso_shape.pentagon, left, top, width, height) shape.text = 'step 1' left += width - inches(0.4) width = inches(2.0) for n in range(2, 6): shape = shapes.add_shape(mso_shape.chevron, left, top, width, height) shape.text = f'step {n}' left += width - inches(0.4)
添加表格
最后,我们添加一个表格:
slide = prs.slides.add_slide(prs.slide_layouts[5]) shapes = slide.shapes shapes.title.text = 'adding a table' table = shapes.add_table(2, 2, inches(2.0), inches(2.0), inches(6.0), inches(0.8)).table table.columns[0].width = inches(2.0) table.columns[1].width = inches(4.0) table.cell(0, 0).text = 'foo' table.cell(0, 1).text = 'bar' table.cell(1, 0).text = 'baz' table.cell(1, 1).text = 'qux'
保存ppt文档
完成所有编辑后,我们将文档保存为test.pptx
:
prs.save('test.pptx')
效果预览
通过以上步骤,我们可以快速创建一个包含标题、子弹点、文本框、图片、自定义形状和表格的ppt文档。python-pptx库提供了丰富的功能,可以满足我们大部分的演示文稿制作需求。
以上就是使用python-pptx库进行ppt文档自动化处理的简介。希望这篇文章能帮助你提高工作效率!
发表评论