使用 python pptx 模块在 PowerPoint 中插入一行

Insert a line into a PowerPoint using python pptx module

以下代码行显示了如何使用 python 在 PowerPoint 幻灯片中绘制线条。但是,下面列出的四个以英寸为单位的参数只取正值,不能倒退。有没有其他方法可以在 PowerPoint 幻灯片中画线?

from pptx.enum.shapes import MSO_SHAPE
line1 = slide.shapes.add_shape(MSO_SHAPE.LINE_INVERSE, Inches(6), Inches(6), Inches(1), Inches(2))

您可以使用连接器对象而不是形状对象绘制线条,(形状需要 x、y、高度和宽度,而 powerpoint 不能处理负高度)

来自docs

Lines are a sub-category of auto shape that differ in certain properties and behaviors. In particular, they have a start point and end point in addition to extents (left, top, width, height).

Connectors are based on the element and have one of a handful of different preset geometry values, such as line. Freeform connectors, despite the name, are not connectors, and are a custom geometry shape based on the p:sp element.

Connectors can be “connected” to an auto shape such that a connected end point remains connected when the auto shape is moved. This relies on a concept of “connection points” on the auto shape. These connections points are preset features of the auto shape, similar to how adjustment points are pre-defined. Connection points are identified by index.

使用下面的代码可以绘制一条从 x = 4 英寸到 x= 2 英寸的直线。

from pptx.enum.shapes import MSO_CONNECTOR
from pptx import Presentation 


# Make sure you have a presentation called test1.pptx in your working directory


prs = Presentation(pptx='test1.pptx')
slide = prs.slides.add_slide(prs.slide_layouts[1])
#shapes.add_connector(MSO_CONNECTOR.STRAIGHT, start_x, start_y, end_x, end_y


line1=slide.shapes.add_connector(MSO_CONNECTOR.STRAIGHT, Inches(4), Inches(2), Inches(1), Inches(2))

prs.save('test2.pptx')