在Apache POI中改变pptx幻灯片主文件的字体。

问题描述 投票:0回答:1

我正在使用Apache POI来修改一个pptx。我想一次性改变整个pptx的字体。

我知道在Powerpoint中,通过改变主题的字体可以做到这一点(如果幻灯片都使用这些字体的话),但是我无法通过Apache POI来实现。

到目前为止,我发现,我可以通过使用以下方法来设置单个XSLFTextRun的字体系列 run.setFontFamily(HSSFFont.FONT_ARIAL).

编辑:我发现XSLFSlideMaster的XSLFTheme类确实有一个getMajorFont()和一个getMinorFont()方法。我想这些可能是我需要改变的字体,但这些字段没有设置器。

谢谢你的帮助!我使用Apache POI来修改字体。

java apache-poi powerpoint
1个回答
0
投票

如果你的尝试是想做和 更改PowerPoint中的默认字体那么这就改变了所使用主题中字体方案的大字体和小字体。

你可以得到 XSLFTheme 幻灯片中的每一张幻灯片,所以也从主幻灯片中获取。但正如你所发现的那样,有getter,但没有大字体和小字体的setter。所以我们需要使用低级的 ooxml-schemas 类。

以下代码示例提供了 setMajorFontsetMinorFont 方法,设置主题中大字体和小字体的字面,可以是拉丁文、东亚文或复杂字体。

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.xslf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.main.*;

public class PowerPointChangeThemeFonts {

 enum Script {
  LATIN, //Latin script
  EA, //east Asia script
  CS //complex script
 }

 static void setMajorFont(XSLFTheme theme, Script script, String typeFace) {
  CTOfficeStyleSheet styleSheet = theme.getXmlObject();
  CTBaseStyles themeElements = styleSheet.getThemeElements();
  CTFontScheme fontScheme = themeElements.getFontScheme();
  CTFontCollection fontCollection = fontScheme.getMajorFont();
  CTTextFont textFont = null;
  if (script == Script.LATIN) {
   textFont = fontCollection.getLatin();
   textFont.setTypeface(typeFace);
  } else if (script == Script.EA) {
   textFont = fontCollection.getEa();
   textFont.setTypeface(typeFace);
  } else if (script == Script.CS) {
   textFont = fontCollection.getCs();
   textFont.setTypeface(typeFace);
  }
 }

 static void setMinorFont(XSLFTheme theme, Script script, String typeFace) {
  CTOfficeStyleSheet styleSheet = theme.getXmlObject();
  CTBaseStyles themeElements = styleSheet.getThemeElements();
  CTFontScheme fontScheme = themeElements.getFontScheme();
  CTFontCollection fontCollection = fontScheme.getMinorFont();
  CTTextFont textFont = null;
  if (script == Script.LATIN) {
   textFont = fontCollection.getLatin();
   textFont.setTypeface(typeFace);
  } else if (script == Script.EA) {
   textFont = fontCollection.getEa();
   textFont.setTypeface(typeFace);
  } else if (script == Script.CS) {
   textFont = fontCollection.getCs();
   textFont.setTypeface(typeFace);
  }
 }

 public static void main(String args[]) throws Exception {

  XMLSlideShow slideShow = new XMLSlideShow(new FileInputStream("./PPTX.pptx"));

  if (slideShow.getSlideMasters().size() > 0) {
   XSLFSlideMaster master = slideShow.getSlideMasters().get(0);
   XSLFTheme theme = master.getTheme();
   setMajorFont(theme, Script.LATIN, "Courier New");
   setMinorFont(theme, Script.LATIN, "Courier New");
  }

  FileOutputStream out = new FileOutputStream("./PPTXNew.pptx");
  slideShow.write(out);
  out.close();
  slideShow.close();
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.