如何使用docx4j添加PPT笔记

时间:2013-12-06 15:50:00

标签: java powerpoint docx4j

我正在使用库docx4j创建PPT文件。我已经能够创建带有文本和图像的幻灯片,但我无法为它们添加注释。

我正在创建这样的幻灯片:

MainPresentationPart pp = (MainPresentationPart)presentationParts.get(new PartName("/ppt/presentation.xml"));
SlideLayoutPart layoutPart = (SlideLayoutPart)presentationParts.get(new PartName("/ppt/slideLayouts/slideLayout1.xml"));
SlidePart slidePart = PresentationMLPackage.createSlidePart(pp, layoutPart, new PartName("/ppt/slides/slide" + ++slideNumber + ".xml"));

因此我可以向正文添加文本或图像,但是当我尝试访问字段slidePart.notes时,它为null。我试图初始化它

slidePart.setPartShortcut(new NotesSlidePart());

然后注释中的所有内容都为空,我没有取得任何成就。

那么,有没有人有一个如何在PPT文件中添加注释的工作示例?

非常感谢

1 个答案:

答案 0 :(得分:2)

这还不够:

slidePart.setPartShortcut(new NotesSlidePart());

您需要通过调用addTargetPart将注释幻灯片部分显式添加到幻灯片部分(以便正确设置关系)。

但是,考虑到pptx格式的工作原理,你还有更多工作要做。要查看所需的部件,请将pptx上传到docx4j webapp。这是我刚才写的代码:

    // Now add notes slide.
    // 1. Notes master
    NotesMasterPart nmp = new NotesMasterPart();
    NotesMaster notesmaster = (NotesMaster)XmlUtils.unmarshalString(notesMasterXml, Context.jcPML);
    nmp.setJaxbElement(notesmaster);
    // .. connect it to /ppt/presentation.xml
    Relationship ppRelNmp = pp.addTargetPart(nmp);
    /*
     *  <p:notesMasterIdLst>
            <p:notesMasterId r:id="rId3"/>
        </p:notesMasterIdLst>
     */
    pp.getJaxbElement().setNotesMasterIdLst(createNotesMasterIdListPlusEntry(ppRelNmp.getId()));

    // .. NotesMasterPart typically has a rel to a theme 
    // .. can we get away without it? 
    // Nope .. read this in from a file
    ThemePart themePart = new ThemePart(new PartName("/ppt/theme/theme2.xml"));
        // TODO: read it from a string instead
    themePart.unmarshal(
            FileUtils.openInputStream(new File(System.getProperty("user.dir") + "/theme2.xml"))
        );      
    nmp.addTargetPart(themePart);

    // 2. Notes slide
    NotesSlidePart nsp = new NotesSlidePart();
    Notes notes = (Notes)XmlUtils.unmarshalString(notesXML, Context.jcPML);
    nsp.setJaxbElement(notes);
    // .. connect it to the slide
    slidePart.addTargetPart(nsp);
    // .. it also has a rel to the slide
    nsp.addTargetPart(slidePart);
    // .. and the slide master
    nsp.addTargetPart(nmp);

您可以在https://github.com/plutext/docx4j/blob/master/src/samples/pptx4j/org/pptx4j/samples/SlideNotes.java

找到完整的示例