在编辑PowerPoint文档时,出于美观或实际需求考虑,我们有时会对某个幻灯片中的文本字体样式进行设置,比如,改变字体名称/字体大小,更改字体颜色,给字体加粗,添加下划线或设置斜体。当需要设置的文本很多,手动逐一进行上述操作会很麻烦,本文就将介绍一种很方便快捷的方式——通过后端调用Java代码进行自动操作。
操作工具:Free Spire.Presentation for Java (可在E-iceblue中文官网获取,解压后在lib文件夹下找到Spire.Presentation.jar,然后将其手动添加到Java项目中;或者是创建Maven仓库,在pom.xml文件中键入以下代码进行产品导入)
代码示例
以下是代码操作步骤:
- 创建Presentation实例并使用Presentation.loadFromFile()方法加载PowerPoint示例文档;
- 使用Presentation.getSlides().get()方法获取指定幻灯片,并用ISlide接口提供的方法获取指定文本形状;
- 使用IAutoShape.getTextFrame()方法获取TextFrame对象,再使用ITextFrameProperties接口提供的方法获取这个对象中的指定段落;
- 使用ParagraphEx.getTextRanges().get()方法获取段落中的文本内容;
- 使用FillFormat.setFillType(FillFormatType value)方法设置文本内容的填充类型,使用ColorFormat.setColor(ColorType value)方法设置填充颜色;
- 用同样的方法可以指定其他文本形状,以及设置指定段落中字体形式。比如,字体加粗,设置斜体,添加下划线,更改字体名称及大小;
- 最后使用Presentation.saveToFile()方法保存结果文档至指定路径。
import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;
import java.awt.*;
public class ChangeFontStyles {
public static void main(String[] args) throws Exception {
//创建Presentation实例
Presentation presentation = new Presentation();
//加载PowerPoint示例文档
presentation.loadFromFile("C:\Users\Tina\Desktop\sample.pptx");
//获取第一个文本形状
IAutoShape shape1 = (IAutoShape) presentation.getSlides().get(0).getShapes().get(0);
//获取形状中的第一个段落并更改其字体颜色
ParagraphEx paragraph = shape1.getTextFrame().getParagraphs().get(0);
for (int i = 0; i < paragraph.getTextRanges().getCount(); i++) {
PortionEx textRange = paragraph.getTextRanges().get(i);
textRange.getFormat().getFill().setFillType(FillFormatType.SOLID);
textRange.getFormat().getFill().getSolidColor().setColor(Color.red);
}
//获取第二个文本形状
IAutoShape shape2 = (IAutoShape) presentation.getSlides().get(0).getShapes().get(1);
//获取形状中的第一个段落并将其文字加粗,设置斜体和下划线
paragraph = shape2.getTextFrame().getParagraphs().get(0);
for (int i = 0; i < paragraph.getTextRanges().getCount(); i++) {
PortionEx textRange = paragraph.getTextRanges().get(i);
textRange.getFormat().isBold(TriState.TRUE);
textRange.getFormat().isItalic(TriState.TRUE);
textRange.getFormat().setTextUnderlineType(TextUnderlineType.DASHED);
}
//获取形状中的第6个段落并更改其字体名称及大小
paragraph = shape2.getTextFrame().getParagraphs().get(5);
for (int i = 0; i < paragraph.getTextRanges().getCount(); i++) {
PortionEx textRange = paragraph.getTextRanges().get(i);
textRange.getFormat().setEastAsianFont(new TextFont("黑体"));
textRange.getFormat().setFontHeight(30f);
}
//保存结果文档到指定路径
presentation.saveToFile("output/ChangeFontStyles.pptx", FileFormat.PPTX_2013);
}
}