OpenXML中如何将Shape内的文本居中对齐?
解决OpenXML Shape中文本居中对齐的问题
你的代码未配置文本对齐规则,要实现Shape内文本居中,需处理段落水平对齐和文本框垂直对齐(按需选择),以下是修改后的完整代码:
private void AddTextAndSetCenter(String file) { using (var presentation = PresentationDocument.Open(file, true)) { var tree = presentation .PresentationPart .SlideParts .ElementAt(0) .Slide .Descendants<DocumentFormat.OpenXml.Presentation.ShapeTree>() .First(); var shape = new DocumentFormat.OpenXml.Presentation.Shape(); shape.NonVisualShapeProperties = new DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties(); shape.NonVisualShapeProperties.Append(new DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties { Name = "My Shape", Id = (UInt32)tree.ChildElements.Count - 1 }); shape.NonVisualShapeProperties.Append(new DocumentFormat.OpenXml.Presentation.NonVisualShapeDrawingProperties()); shape.NonVisualShapeProperties.Append(new DocumentFormat.OpenXml.Presentation.ApplicationNonVisualDrawingProperties()); shape.ShapeProperties = new DocumentFormat.OpenXml.Presentation.ShapeProperties(); shape.ShapeProperties.Transform2D = new DocumentFormat.OpenXml.Drawing.Transform2D(); shape.ShapeProperties.Transform2D.Append(new DocumentFormat.OpenXml.Drawing.Offset { X = 10000000, Y = 2000000, }); shape.ShapeProperties.Transform2D.Append(new DocumentFormat.OpenXml.Drawing.Extents { Cx = 1000000, Cy = 1000000, }); shape.ShapeProperties.Append(new PresetGeometry { Preset = ShapeTypeValues.Rectangle }); var outline = new A.Outline(new A.SolidFill(new A.RgbColorModelHex { Val = "000000" })); outline.Width = (5 * 12700); shape.ShapeProperties.Append(outline); // 1. 设置文本框垂直居中(可选,按需开启) var bodyProperties = new A.BodyProperties { Vertical = TextVerticalValues.Center }; // 2. 设置段落水平居中 var paragraphProperties = new A.ParagraphProperties { Alignment = TextAlignmentTypeValues.Center }; // 创建带对齐配置的TextBody和Paragraph shape.TextBody = new TextBody( bodyProperties, new A.ListStyle(), new A.Paragraph( paragraphProperties, new A.Run(new A.Text("Hello")) ) ); tree.AppendChild(shape); } }
关键修改说明:
- 段落水平居中:通过
A.ParagraphProperties的Alignment属性设置为TextAlignmentTypeValues.Center,控制文本在段落内的水平方向居中。 - 文本框垂直居中:通过
A.BodyProperties的Vertical属性设置为TextVerticalValues.Center,让文本在Shape的高度范围内上下居中,若仅需水平居中可去掉此配置。
内容的提问来源于stack exchange,提问作者Pasit Panphet
相关产品推荐
相关产品推荐

