我该如何使用C#更改PowerPoint中的TextRange字体颜色?

7
我使用C#创建了一个PowerPoint演示文稿:
PowerPoint.Application powerpointApplication;
PowerPoint.Presentation pptPresentation;
PowerPoint.Slide Slide;

// Create an instance of PowerPoint.
powerpointApplication = new PowerPoint.ApplicationClass();

// Create a PowerPoint presentation.
pptPresentation = powerpointApplication.Presentations.Add(
Microsoft.Office.Core.MsoTriState.msoTrue);


// Create empty slide
Slide = pptPresentation.Slides.Add(1, PowerPoint.PpSlideLayout.ppLayoutBlank);

TextRange objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
objTextRng.Text = "Remote sensing calendar 1";
objTextRng.Font.Name = "Comic Sans MS";
objTextRng.Font.Size = 48;
// TODO: change color
// objTextRng.Font.Color 



// Save presentation
pptPresentation.SaveAs( BasePath + "result\\2_example.ppt", 
                       PowerPoint.PpSaveAsFileType.ppSaveAsDefault, 
                       MsoTriState.msoTrue // TODO: что за параметр???
                      );
pptPresentation.Close();

现在,我该如何改变objTextRng的字体颜色呢?
4个回答

7
以下代码将把字体颜色设置为红色:
objTextRng.Font.Color.RGB = Color.Red.ToArgb();

如果您想指定不同的颜色,可以使用其他预定义颜色之一,或者使用Color.FromArgb方法指定自己的RGB值。
无论哪种方式,都要确保调用您使用的Color对象上的ToArgb方法RGB属性需要指定一个RGB颜色值。

1
实际上,这将其设置为蓝色,尽管PowerPoint解释颜色的方式是BGR格式。将字体颜色设置为红色最简单(也是最不优雅)的方法就是在十六进制中指定颜色(反转R和B字节):range.Font.Color.RGB = 0x0000FF; - 同样,蓝色将是 range.Font.Color.RGB = 0xFF0000;,以此类推。(*:实际上它是RGB格式,但它是大端存储,这意味着字节从右到左存储,而不是从左到右。) - BrainSlugs83

5
使用此方法处理PPTX 2007格式的文件。
    private int BGR(Color color)
    {
        // PowerPoint's color codes seem to be reversed (i.e., BGR) not RGB
        //      0x0000FF    produces RED not BLUE
        //      0xFF0000    produces BLUE not RED
        // so we have to produce the color "in reverse"

        int iColor = color.R + 0xFF * color.G + 0xFFFF * color.B;

        return iColor;
    }

例如
    shape.TextFrame.TextRange.Font.Color.RGB = BGR(Color.Red);  

2
这在Powerpoint 2013中似乎仍然是这种情况(我猜它是相同的格式)。有点傻,当你将Color.RGB设置为红色时,没有这个函数你会得到蓝色。 :) - Thomas Glaser

0

我认为这个MSDN页面可以解释它。

编辑: 但是这只能解释如何在VBScript中完成。你可以看到TextRange对象有一个Font属性。这返回描述这里Font对象。这些资源向您展示了您可以访问RGB属性。您可以像Cody告诉您的那样设置它。如果需要更多信息,请参考我刚才指出的MSDN部分。


你肯定可以从那个页面中获取解释,但它讨论的是DropCap而不是TextRange对象,并且示例代码是用VB 6.0/VBScript编写的,这不容易转换成C#。特别地,在C#中没有RGB函数。 - Cody Gray
我同意,我只是不想只放链接。有时候很烦人,所以我复制了代码示例。 - Philippe Lavoie
然而,问题在于代码示例无法在C#中运行,因为该问题已被标记。没有RGB函数,您必须像我的答案建议的那样(这是首选方法)或导入Microsoft.VisualBasic命名空间以使用Information.RGB函数。 - Cody Gray
各位:那个链接是关于Publisher 2010的,与PowerPoint不同。 - Todd Main

0

objTextRng.Font.Color.RGB = System.Drawing.ColorTranslator.ToOl(System.Drawing.Color.Blue);

objTextRng.Font.Color.RGB = System.Drawing.ColorTranslator.ToOl(System.Drawing.Color.Blue);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接