使用Docx4j操作PPT指南系列(二)

使用Docx4j操作PPT指南系列(二)

—— 使用xml 添加标题与副标题

在上一章节中我们尝试了创建一个新的PPT文件,并且在文件中添加了一个新页,在本章中我们将会了解到,如何在这些页面中添加标题。

首先我们来看下面的图片

这是一个典型的PPT封面,接下来我们就要通过xml来向封面中的标题框内添加内容。代码如下:

public static void main(String[] args) {try {

// 加载一个ppt文件作为模板PresentationMLPackage presentationMLPackage = PresentationMLPackage.load(new File(PSMSConstants.REPORT_PPT2007_TEMPLATE_PATH));

SlidePart slidePart = (SlidePart) presentationMLPackage.getParts().getParts().get(new PartName("/ppt/slides/slide1.xml"));

// 读取XML生成形状Shape title = (Shape) XmlUtils.unmarshalString(getSlideTitle("使用Docx4j操作PPT指南系列(二)"), Context.jcPML);

// 注意,主标题与副标题的xml是不同的Shape subtitle = (Shape) XmlUtils.unmarshalString(getSubSlideTitle("使用xml 添加标题与副标题"), Context.jcPML);((Sld) slidePart.getJaxbElement()).getCSld().getSpTree().getSpOrGrpSpOrGraphicFrame().add(title);((Sld) slidePart.getJaxbElement()).getCSld().getSpTree().getSpOrGrpSpOrGraphicFrame().add(subtitle);

String path = "c://test.pptx";

presentationMLPackage.save(new java.io.File(path));

} catch (Docx4JException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JAXBException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}

/** * 生成标题 * * @param preset * @return */public static String getSlideTitle(String preset) {

return "<p:sp xmlns:a=\&;\&; "+ "xmlns:r=\&;\&; "+ "xmlns:p=\&;\&;>"+ "<p:nvSpPr><p:cNvPr id=\&;2\&; name=\&;标题 1\&;/>"+ "<p:cNvSpPr><a:spLocks noGrp=\&;1\&;/>"+ "</p:cNvSpPr><p:nvPr><p:ph type=\&;title\&;/>"+ "</p:nvPr></p:nvSpPr><p:spPr/><p:txBody>"+ "<a:bodyPr/><a:lstStyle/><a:p><a:r>"+ "<a:rPr lang=\&;en-US\&; altLang=\&;zh-CN\&; dirty=\&;0\&; err=\&;1\&; smtClean=\&;0\&;/>"+ "<a:t>"+ preset+ "</a:t></a:r>"+ "<a:endParaRPr lang=\&;zh-CN\&; altLang=\&;en-US\&; dirty=\&;0\&;/></a:p>"+ "</p:txBody></p:sp>";

}

/** * 添加副标题 * * @param preset * @return */public static String getSubSlideTitle(String preset) {

return "<p:sp xmlns:a=\&;\&; "+ "xmlns:r=\&;\&; "+ "xmlns:p=\&;\&;>"+ "<p:nvSpPr><p:cNvPr id=\&;4\&; name=\&;副标题 3\&;/>"+ "<p:cNvSpPr><a:spLocks noGrp=\&;1\&;/>"+ "</p:cNvSpPr><p:nvPr><p:ph type=\&;subTitle\&; idx=\&;1\&;/>"+ "</p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr>"+ "<a:normAutofit lnSpcReduction=\&;10000\&;/></a:bodyPr>"+ "<a:lstStyle/><a:p><a:r><a:rPr lang=\&;en-US\&; altLang=\&;zh-CN\&; dirty=\&;0\&; smtClean=\&;0\&;/>"+ "<a:t>"+ preset+ "</a:t></a:r><a:endParaRPr lang=\&;zh-CN\&; altLang=\&;en-US\&; dirty=\&;0\&;/>"+ "</a:p></p:txBody></p:sp>";}

切忌贪婪,恨不得一次玩遍所有传说中的好景点,

使用Docx4j操作PPT指南系列(二)

相关文章:

你感兴趣的文章:

标签云: