protected static void insertXMLData(
     WordprocessingMLPackage wmlPackage, String storageId, Document xmlDocument)
     throws Docx4JException {
   CustomXmlDataStorage customXmlDataStorage = null;
   CustomXmlDataStoragePart customXmlDataStoragePart = null;
   customXmlDataStoragePart =
       (CustomXmlDataStoragePart)
           wmlPackage.getCustomXmlDataStorageParts().get(storageId.toLowerCase());
   customXmlDataStoragePart.getData().setDocument(xmlDocument);
 }
  public static CustomXmlDataStoragePart injectCustomXmlDataStoragePart(Part parent)
      throws Exception {

    org.docx4j.openpackaging.parts.CustomXmlDataStoragePart customXmlDataStoragePart =
        new org.docx4j.openpackaging.parts.CustomXmlDataStoragePart();
    // Defaults to /customXml/item1.xml

    CustomXmlDataStorage data = new CustomXmlDataStorageImpl();
    data.setDocument(createCustomXmlDocument());

    customXmlDataStoragePart.setData(data);
    parent.addTargetPart(customXmlDataStoragePart, AddPartBehaviour.RENAME_IF_NAME_EXISTS);

    return customXmlDataStoragePart;
  }
  public static void addProperties(CustomXmlDataStoragePart customXmlDataStoragePart)
      throws InvalidFormatException {

    CustomXmlDataStoragePropertiesPart part = new CustomXmlDataStoragePropertiesPart();

    org.docx4j.customXmlProperties.ObjectFactory of =
        new org.docx4j.customXmlProperties.ObjectFactory();

    DatastoreItem dsi = of.createDatastoreItem();
    String newItemId = "{" + UUID.randomUUID().toString() + "}";
    dsi.setItemID(newItemId);

    part.setJaxbElement(dsi);

    customXmlDataStoragePart.addTargetPart(part);
  }
  /** @param args */
  public static void main(String[] args) throws Exception {

    String inputfilepath =
        System.getProperty("user.dir") + "/sample-docs/word/databinding/invoice.docx";

    String data = System.getProperty("user.dir") + "/sample-docs/word/databinding/invoice-data.xml";

    WordprocessingMLPackage wordMLPackage =
        WordprocessingMLPackage.load(new java.io.File(inputfilepath));

    filepathprefix = inputfilepath.substring(0, inputfilepath.lastIndexOf("."));
    System.out.println(filepathprefix);

    StringBuilder timingSummary = new StringBuilder();

    // Find custom xml item id and inject data_file.xml
    long startTime = System.currentTimeMillis();
    CustomXmlDataStoragePart customXmlDataStoragePart =
        CustomXmlDataStoragePartSelector.getCustomXmlDataStoragePart(wordMLPackage);
    if (customXmlDataStoragePart == null) {
      throw new RuntimeException("no xml");
    }
    customXmlDataStoragePart.getData().setDocument(new FileInputStream(new File(data)));
    long endTime = System.currentTimeMillis();
    timingSummary.append("\nmerge data: " + (endTime - startTime));
    System.out.println("data merged");

    SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
    saver.save(new File(System.getProperty("user.dir") + "/OUT_injected.docx"));

    // Process conditionals and repeats
    startTime = System.currentTimeMillis();
    OpenDoPEHandler odh = new OpenDoPEHandler(wordMLPackage);
    odh.preprocess();
    endTime = System.currentTimeMillis();
    timingSummary.append("OpenDoPEHandler: " + (endTime - startTime));

    //		System.out.println(
    //				XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
    //				);
    saver.save(filepathprefix + "_1_preprocessed.docx");
    System.out.println("Saved: " + filepathprefix + "_1_preprocessed.docx");

    startTime = System.currentTimeMillis();
    OpenDoPEIntegrity odi = new OpenDoPEIntegrity();
    odi.process(wordMLPackage);
    endTime = System.currentTimeMillis();
    timingSummary.append("\nOpenDoPEIntegrity: " + (endTime - startTime));

    //		System.out.println(
    //				XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
    //				);
    saver = new SaveToZipFile(wordMLPackage);
    saver.save(filepathprefix + "_2_integrity.docx");
    System.out.println("Saved: " + filepathprefix + "_2_integrity.docx");

    // Apply the bindings
    saver = new SaveToZipFile(wordMLPackage);

    BindingHandler.setHyperlinkStyle("Hyperlink");
    startTime = System.currentTimeMillis();

    //			AtomicInteger bookmarkId = odh.getNextBookmarkId();
    AtomicInteger bookmarkId = new AtomicInteger();

    BindingHandler bh = new BindingHandler(wordMLPackage);
    bh.setStartingIdForNewBookmarks(bookmarkId);
    bh.applyBindings(wordMLPackage.getMainDocumentPart());

    endTime = System.currentTimeMillis();
    timingSummary.append("\nBindingHandler.applyBindings: " + (endTime - startTime));
    //		System.out.println(
    //				XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
    //				);
    saver.save(filepathprefix + "_3_bound.docx");
    System.out.println("Saved: " + filepathprefix + "_3_bound.docx");

    // Either demonstrate reverter, or stripping of controls;
    // you can't do both. So comment out one or the other.
    //		reverter(inputfilepath, filepathprefix + "_bound.docx");
    //
    // Strip content controls
    startTime = System.currentTimeMillis();
    RemovalHandler rh = new RemovalHandler();
    rh.removeSDTs(wordMLPackage, Quantifier.ALL);
    endTime = System.currentTimeMillis();
    timingSummary.append("\nRemovalHandler: " + (endTime - startTime));

    saver.save(filepathprefix + "_4_stripped.docx");
    System.out.println("Saved: " + filepathprefix + "_4_stripped.docx");

    System.out.println(timingSummary);
  }
Esempio n. 5
0
  public static void apply(WordprocessingMLPackage otherPackage, Alterations alterations)
      throws Docx4JException, JAXBException {

    if (alterations.getContentTypes() != null) {
      log.info("replacing [Content_Types].xml");
      ContentTypeManager newCTM = new ContentTypeManager();
      newCTM.parseContentTypesFile(new ByteArrayInputStream(alterations.getContentTypes()));
      otherPackage.setContentTypeManager(newCTM);
    }

    if (alterations.isEmpty()) return;

    // -- Deletions
    List<PartName> removedParts = new ArrayList<PartName>();

    for (Alteration a : alterations.getPartsDeleted()) {

      org.docx4j.xmlPackage.Part xmlpart = a.getPart();

      // These deleted parts are likely to be attached to
      // to otherPackage, but there is no requirement for
      // that to be so.  In other words, you could try
      // to apply the alterations to some third docx.

      // It might have already been deleted as a consequence
      // of recursive deletion...
      if (removedParts.contains(xmlpart.getName())) continue;

      // Design decision: how to find owning rels part?
      // Since part might not be from this package, can't do:
      // part.getOwningRelationshipPart().removePart(p.getPartName())
      // We could store the info when AlteredParts is run,
      // but lets try to get away without that...
      // If a part has been deleted, we know its owning rels will
      // have been modified or deleted.  So look for that.
      // BUT IT WON'T BE THERE IF ITS BEEN DELETED! DOH!
      // So we have to store the info when AlteredParts is run
      // after all.

      Part parentPart = otherPackage.getParts().get(a.getSourcePartName());
      if (a.getPart().getContentType().equals(ContentTypes.RELATIONSHIPS_PART)) {
        parentPart.setRelationships(null);
      } else {
        removedParts.addAll(
            parentPart.getRelationshipsPart().removePart(new PartName(xmlpart.getName())));
      }
    }

    // -- Modifications
    for (Alteration a : alterations.getPartsModified()) {

      log.info("Applying modifications to part: " + a.getPart().getName());

      if (a.getPart().getContentType().equals(ContentTypes.RELATIONSHIPS_PART)) {

        RelationshipsPart newRP = null; // FlatOpcXmlImporter.createRelationshipsPart(a.getPart());

        if (a.getSourcePartName().equals("/")) {
          newRP = otherPackage.getRelationshipsPart(true);
          //					otherPackage.setRelationships(newRP);
          //					newRP.setSourceP(otherPackage);
        } else {
          Part parentPart = otherPackage.getParts().get(a.getSourcePartName());
          newRP = parentPart.getRelationshipsPart(true);
          //					parentPart.setRelationships(newRP);
          //					newRP.setSourceP(parentPart);
        }
        FlatOpcXmlImporter.populateRelationshipsPart(newRP, a.getPart().getXmlData().getAny());

      } else {

        Part targetPart = otherPackage.getParts().get(new PartName(a.getPart().getName()));

        if (targetPart == null) {
          log.error(
              "Couldn't find " + a.getPart().getName() + " @ " + a.getSourcePartName().getName());
          continue;
        }

        Part tmpPart =
            FlatOpcXmlImporter.getRawPart(otherPackage.getContentTypeManager(), a.getPart(), null);

        if (targetPart instanceof JaxbXmlPart) {
          ((JaxbXmlPart) targetPart).setJaxbElement(((JaxbXmlPart) tmpPart).getJaxbElement());

        } else if (targetPart instanceof XmlPart) {

          ((XmlPart) targetPart).setDocument(((XmlPart) tmpPart).getDocument());

        } else if (targetPart instanceof CustomXmlDataStoragePart) {

          ((CustomXmlDataStoragePart) targetPart)
              .setData(((CustomXmlDataStoragePart) tmpPart).getData());
          // TODO: check that

        } else if (targetPart instanceof BinaryPart) {

          ((BinaryPart) targetPart).setBinaryData(((BinaryPart) tmpPart).getBuffer());

        } else {
          log.error("TODO: handle " + targetPart.getClass().getName());
        }
      }
    }

    // -- Additions
    for (Alteration a : alterations.getPartsAdded()) {

      log.info("Adding part: " + a.getPart().getName());

      if (a.getPart().getContentType().equals(ContentTypes.RELATIONSHIPS_PART)) {

        RelationshipsPart newRP = null; // FlatOpcXmlImporter.createRelationshipsPart(a.getPart());

        if (a.getSourcePartName().equals("/")) {
          newRP = otherPackage.getRelationshipsPart(true);
          //					otherPackage.setRelationships(newRP);
          //					newRP.setSourceP(otherPackage);
        } else {
          Part parentPart = otherPackage.getParts().get(a.getSourcePartName());
          newRP = parentPart.getRelationshipsPart(true);
          //					parentPart.setRelationships(newRP);
          //					newRP.setSourceP(parentPart);
        }
        FlatOpcXmlImporter.populateRelationshipsPart(newRP, a.getPart().getXmlData().getAny());

      } else {

        Part parentPart = otherPackage.getParts().get(a.getSourcePartName());
        Part newPart =
            FlatOpcXmlImporter.getRawPart(otherPackage.getContentTypeManager(), a.getPart(), null);

        // There will already be a rel for the new part,
        // since we will already have modified or added the rels part
        // so don't do AddTargetPart (which will probably create a new rel id,
        // which will cause problems)

        newPart.setOwningRelationshipPart(parentPart.getRelationshipsPart());
        newPart
            .getSourceRelationships()
            .add(parentPart.getRelationshipsPart().getRel(new PartName(a.getPart().getName())));
        otherPackage.getParts().put(newPart);
        newPart.setPackage(otherPackage);

        // TODO: add content type if necessary
      }
    }
  }