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 block e.printStackTrace(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 生成标题 * * @param preset * @return */ public static String getSlideTitle(String preset) { return "<p:sp xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" " + "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" " + "xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\">" + "<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=\"http://schemas.openxmlformats.org/drawingml/2006/main\" " + "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" " + "xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\">" + "<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>"; } |