Example #1
0
  /**
   * Creates document footer including page number
   *
   * @param doc WordprocessingMLPackage for the document.
   * @throws InvalidFormatException
   */
  private void createFooter(WordprocessingMLPackage doc) throws InvalidFormatException {
    MainDocumentPart content = doc.getMainDocumentPart();

    // Create footer
    FooterPart footer = new FooterPart();

    Ftr ftr = objectFactory.createFtr();
    P footerParagraph = objectFactory.createP();

    setStyle(footerParagraph, "footer");

    PPr parProps = objectFactory.createPPr();
    Jc al = objectFactory.createJc();
    al.setVal(JcEnumeration.RIGHT);
    parProps.setJc(al);
    footerParagraph.setPPr(parProps);

    // Add field start
    R run = objectFactory.createR();
    FldChar fldChar = objectFactory.createFldChar();
    fldChar.setFldCharType(STFldCharType.BEGIN);
    run.getContent().add(fldChar);
    footerParagraph.getContent().add(run);

    // Add pageNumber field
    run = objectFactory.createR();
    Text txt = objectFactory.createText();
    txt.setSpace("preserve");
    txt.setValue(" PAGE   \\* MERGEFORMAT ");
    run.getContent().add(objectFactory.createRInstrText(txt));
    footerParagraph.getContent().add(run);

    // Add field end
    run = objectFactory.createR();
    fldChar = objectFactory.createFldChar();
    fldChar.setFldCharType(STFldCharType.END);
    run.getContent().add(fldChar);
    footerParagraph.getContent().add(run);

    ftr.getContent().add(footerParagraph);
    footer.setJaxbElement(ftr);

    Relationship rel = content.addTargetPart(footer);

    // Relate footer to document
    List<SectionWrapper> sections = doc.getDocumentModel().getSections();

    SectPr sectPr = sections.get(sections.size() - 1).getSectPr();

    if (null == sectPr) {
      sectPr = objectFactory.createSectPr();
      content.addObject(sectPr);
      sections.get(sections.size() - 1).setSectPr(sectPr);
    }

    FooterReference footerReference = objectFactory.createFooterReference();
    footerReference.setId(rel.getId());
    footerReference.setType(HdrFtrRef.DEFAULT);
    sectPr.getEGHdrFtrReferences().add(footerReference);
  }
Example #2
0
  /** Example of how to find an object in document.xml via traversal (as opposed to XPath) */
  public static void main(String[] args) throws Exception {

    String inputfilepath = System.getProperty("user.dir") + "/checkbox.docx";

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

    Finder finder = new Finder(FldChar.class); // <----- change this to suit
    new TraversalUtil(documentPart.getContent(), finder);

    System.out.println("got " + finder.results.size() + " of type " + finder.typeToFind.getName());

    for (Object o : finder.results) {

      Object o2 = XmlUtils.unwrap(o);
      // this is ok, provided the results of the Callback
      // won't be marshalled

      if (o2 instanceof org.docx4j.wml.Text) {

        org.docx4j.wml.Text txt = (org.docx4j.wml.Text) o2;

        System.out.println(txt.getValue());

      } else {
        System.out.println(XmlUtils.marshaltoString(o, true, true));
      }
    }
  }
Example #3
0
  /**
   * Create a paragraph containing the string simpleText, without adding it to the document. If
   * passed null, the result is an empty P.
   *
   * @param simpleText
   * @return
   */
  public org.docx4j.wml.P createParagraphOfText(String simpleText) {

    org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
    org.docx4j.wml.P para = factory.createP();

    if (simpleText != null) {
      org.docx4j.wml.Text t = factory.createText();
      t.setValue(simpleText);

      org.docx4j.wml.R run = factory.createR();
      run.getContent().add(t); // ContentAccessor	

      para.getContent().add(run); // ContentAccessor
    }

    return para;
  }
  private void addCellStyle(
      Tc tableCell, BandElement be, String content, P paragraph, Map<String, Object> style) {
    if (style != null) {

      // inner html text
      if (content.startsWith("<html>")) {
        try {
          wordMLPackage
              .getMainDocumentPart()
              .addAltChunk(AltChunkType.Html, content.getBytes(), tableCell);
          tableCell.getContent().add(paragraph);
        } catch (Docx4JException e) {
          e.printStackTrace();
        }
        return;
      }

      Text text = factory.createText();
      text.setValue(content);

      R run = factory.createR();
      run.getContent().add(text);

      paragraph.getContent().add(run);

      setHorizontalAlignment(paragraph, style);

      RPr runProperties = factory.createRPr();

      setFont(tableCell, style, runProperties);
      setCellMargins(tableCell, style);
      setBackground(tableCell, style);
      setVerticalAlignment(tableCell, style);
      setCellBorders(tableCell, style);
      if (be != null) {
        setTextDirection(tableCell, be.getTextRotation());
      }

      run.setRPr(runProperties);

      tableCell.getContent().add(paragraph);
    }
  }
  public org.docx4j.wml.P.Hyperlink newHyperlink(MainDocumentPart mdp, String text, String url) {
    try {
      // We need to add a relationship to word/_rels/document.xml.rels but since its external, we
      // don't use
      // the usual wordMLPackage.getMainDocumentPart().addTargetPart mechanism
      org.docx4j.relationships.ObjectFactory factory = new org.docx4j.relationships.ObjectFactory();
      org.docx4j.relationships.Relationship rel = factory.createRelationship();
      rel.setType(Namespaces.HYPERLINK);
      rel.setTarget(url);
      rel.setTargetMode("External");
      mdp.getRelationshipsPart().addRelationship(rel);
      // addRelationship sets the rel's @Id

      org.docx4j.wml.P.Hyperlink hyp = new org.docx4j.wml.P.Hyperlink();
      hyp.setId(rel.getId());
      R run = Context.getWmlObjectFactory().createR();
      hyp.getContent().add(run);
      RPr rpr = new RPr();
      RStyle rStyle = new RStyle();
      rStyle.setVal("Hyperlink");
      rpr.setRStyle(rStyle);
      run.setRPr(rpr);

      Text t = new Text();
      t.setValue(text);
      run.getContent().add(t);
      //			String hpl = "<w:hyperlink r:id=\"" + rel.getId()
      //					+ "\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" "
      //					+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" >" +
      // "<w:r>" + "<w:rPr>"
      //					+ "<w:rStyle w:val=\"Hyperlink\" />" +
      //					"</w:rPr>" + "<w:t>" + text + "</w:t>" + "</w:r>" + "</w:hyperlink>";
      //			return (org.docx4j.wml.P.Hyperlink) XmlUtils.unmarshalString(hpl);
      return hyp;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * This is where we add the actual styling information. In order to do this we first create a
   * paragraph. Then we create a text with the content of the cell as the value. Thirdly, we create
   * a so-called run, which is a container for one or more pieces of text having the same set of
   * properties, and add the text to it. We then add the run to the content of the paragraph. So far
   * what we've done still doesn't add any styling. To accomplish that, we'll create run properties
   * and add the styling to it. These run properties are then added to the run. Finally the
   * paragraph is added to the content of the table cell.
   */
  private void addStyling(Tc tableCell, String content, boolean bold, String fontSize) {
    P paragraph = factory.createP();

    Text text = factory.createText();
    text.setValue(content);

    R run = factory.createR();
    run.getContent().add(text);

    paragraph.getContent().add(run);

    RPr runProperties = factory.createRPr();
    if (bold) {
      addBoldStyle(runProperties);
    }

    if (fontSize != null && !fontSize.isEmpty()) {
      setFontSize(runProperties, fontSize);
    }

    run.setRPr(runProperties);

    tableCell.getContent().add(paragraph);
  }
Example #7
0
  @Override
  public void write(OutputStream ous) {
    WordprocessingMLPackage doc;

    try {
      doc = WordprocessingMLPackage.createPackage();
      MainDocumentPart content = doc.getMainDocumentPart();

      // Create header and footer
      createHeader(doc);
      createFooter(doc);

      // Add first page
      P docTitle = content.addStyledParagraphOfText("Heading1", p.getTitle());
      alignParagraph(docTitle, JcEnumeration.CENTER);
      addPageBreak(content);

      // Add sections
      Iterator<DocumentSectionInstance> itdsi =
          SWBComparator.sortSortableObject(di.listDocumentSectionInstances());
      while (itdsi.hasNext()) {
        DocumentSectionInstance dsi = itdsi.next();
        SemanticClass cls =
            dsi.getSecTypeDefinition() != null
                    && dsi.getSecTypeDefinition().getSectionType() != null
                ? dsi.getSecTypeDefinition().getSectionType().transformToSemanticClass()
                : null;

        if (null == cls || !dsi.getSecTypeDefinition().isActive()) continue;

        // Add section title
        content.addStyledParagraphOfText("Heading2", dsi.getSecTypeDefinition().getTitle());

        // Gather sectionElement instances
        Iterator<SectionElement> itse =
            SWBComparator.sortSortableObject(dsi.listDocuSectionElementInstances());
        List<SectionElement> sectionElementInstances = new ArrayList<SectionElement>();
        while (itse.hasNext()) {
          SectionElement se = itse.next();
          sectionElementInstances.add(se);
        }

        if (cls.isSubClass(Instantiable.swpdoc_Instantiable, false)) {
          // Get visible props from config
          String[] props = dsi.getSecTypeDefinition().getVisibleProperties().split("\\|");

          // Add properties table
          if (props.length > 0 && !sectionElementInstances.isEmpty()) {
            int writableWidthTwips =
                doc.getDocumentModel()
                    .getSections()
                    .get(0)
                    .getPageDimensions()
                    .getWritableWidthTwips();
            int cellWidthTwips =
                new Double(Math.floor((writableWidthTwips / props.length))).intValue();

            Tbl propsTable =
                TblFactory.createTable(
                    sectionElementInstances.size() + 1, props.length, cellWidthTwips);
            setStyle(propsTable, "TableGrid");

            // Add table header
            Tr headerRow = (Tr) propsTable.getContent().get(0);
            int c = 0;
            for (String prop : props) {
              Tc col = (Tc) headerRow.getContent().get(c++);
              P colContent = objectFactory.createP(); // (P) col.getContent().get(0);
              TcPr cellProps = col.getTcPr();
              cellProps.getTcW().setType(TblWidth.TYPE_DXA);

              Text colText = objectFactory.createText();
              colText.setValue(prop.substring(0, prop.indexOf(";")));
              R colRun = objectFactory.createR();
              colRun.getContent().add(colText);

              setFontStyle(colRun, false, true);

              colContent.getContent().add(colRun);
              col.getContent().set(0, colContent);
              // alignParagraph(colContent, JcEnumeration.CENTER);
              // fillTableCell(col);
            }

            // Add rows
            int r = 1;
            for (SectionElement se : sectionElementInstances) {
              Tr row = (Tr) propsTable.getContent().get(r++);
              c = 0;
              for (String prop : props) {
                Tc col = (Tc) row.getContent().get(c++);
                String idProperty = prop.substring(prop.indexOf(";") + 1, prop.length());
                SemanticProperty sprop =
                    SWBPlatform.getSemanticMgr()
                        .getVocabulary()
                        .getSemanticPropertyById(idProperty);
                P colContent;

                if (null == sprop) {
                  colContent = content.createParagraphOfText("");
                } else {
                  if (!sprop.getPropId().equals(Referable.swpdoc_file.getPropId())) {
                    colContent =
                        content.createParagraphOfText(
                            se.getSemanticObject().getProperty(sprop) != null
                                ? se.getSemanticObject().getProperty(sprop)
                                : "");
                  } else {
                    colContent = content.createParagraphOfText(se.getTitle());
                  }
                }
                col.getContent().set(0, colContent);
                alignParagraph(colContent, JcEnumeration.BOTH);
                setStyle(colContent, "Normal");
              }
            }

            // Add table to document
            content.addObject(propsTable);
          }
        } else if (cls.equals(FreeText.sclass)) {
          XHTMLImporterImpl importer = new XHTMLImporterImpl(doc);
          for (SectionElement se : sectionElementInstances) {
            FreeText freeText = (FreeText) se;
            if (null != se) {
              String sContent = freeText.getText();
              if (null != sContent && !sContent.isEmpty()) {
                sContent =
                    sContent.replace(
                        "<!DOCTYPE html>",
                        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
                sContent =
                    sContent.replace("<html>", "<html xmlns=\"http://www.w3.org/1999/xhtml\">");

                // Override styles and alignment
                List<Object> objects = importer.convert(sContent, null);
                for (Object o : objects) {
                  if (o instanceof Tbl) setStyle((Tbl) o, "TableGrid");
                  if (o instanceof P) {
                    // Fix harcoded runProperties
                    List<Object> pChilds = ((P) o).getContent();
                    for (Object child : pChilds) {
                      if (child instanceof R) {
                        // ((R)child).setRPr(objectFactory.createRPr());
                        RPr rpr = ((R) child).getRPr();
                        if (null != rpr) {
                          rpr.getRFonts().setAsciiTheme(null);
                          rpr.getRFonts().setAscii(null);
                          rpr.getRFonts().setHAnsiTheme(null);
                          rpr.getRFonts().setHAnsi(null);
                        }
                      }
                    }
                    alignParagraph((P) o, JcEnumeration.BOTH);
                    setStyle((P) o, "Normal");
                  }
                }
                content.getContent().addAll(objects);
              }
            }
          }
        } else if (cls.equals(Activity.sclass)) {
          for (SectionElement se : sectionElementInstances) {
            Activity a = (Activity) se;
            if (a.getDescription() != null && !a.getDescription().isEmpty()) {
              XHTMLImporterImpl importer = new XHTMLImporterImpl(doc);
              content.addStyledParagraphOfText("Heading3", a.getTitle());

              String sContent = a.getDescription();
              if (null != sContent && !sContent.isEmpty()) {
                sContent =
                    sContent.replace(
                        "<!DOCTYPE html>",
                        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
                sContent =
                    sContent.replace("<html>", "<html xmlns=\"http://www.w3.org/1999/xhtml\">");

                // Override styles and alignment
                List<Object> objects = importer.convert(sContent, null);
                for (Object o : objects) {
                  if (o instanceof Tbl) setStyle((Tbl) o, "TableGrid");
                  if (o instanceof P) {
                    // Fix harcoded runProperties
                    List<Object> pChilds = ((P) o).getContent();
                    for (Object child : pChilds) {
                      if (child instanceof R) {
                        // ((R)child).setRPr(null);
                        RPr rpr = ((R) child).getRPr();
                        if (null != rpr) {
                          rpr.getRFonts().setAsciiTheme(null);
                          rpr.getRFonts().setAscii(null);
                          rpr.getRFonts().setHAnsiTheme(null);
                          rpr.getRFonts().setHAnsi(null);
                        }
                      }
                    }
                    alignParagraph((P) o, JcEnumeration.BOTH);
                    setStyle((P) o, "Normal");
                  }
                }
                content.getContent().addAll(objects);
              }
            }
          }
        } else if (cls.equals(Model.sclass)) {
          File img = new File(assetsPath + "/" + p.getId() + ".png");
          if (img.exists()) {
            FileInputStream fis = new FileInputStream(img);
            long length = img.length();

            if (length > Integer.MAX_VALUE) {
              log.error("File too large in model generation");
            } else {
              // Read image bytes
              byte[] bytes = new byte[(int) length];
              int offset = 0;
              int numRead = 0;
              while (offset < bytes.length
                  && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
              }

              if (offset < bytes.length) {
                log.error("Could not completely read file " + img.getName());
              }

              fis.close();

              // Generate ImagePart
              BinaryPartAbstractImage imagePart =
                  BinaryPartAbstractImage.createImagePart(doc, bytes);
              Inline inline = imagePart.createImageInline("", "", 0, 1, false);

              // Add image to paragraph
              P p = objectFactory.createP();
              R run = objectFactory.createR();
              p.getContent().add(run);
              Drawing drawing = objectFactory.createDrawing();
              run.getContent().add(drawing);
              drawing.getAnchorOrInline().add(inline);
              content.getContent().add(p);
            }
          }
        }
        addPageBreak(content);
      }
      doc.save(ous);
    } catch (Docx4JException | FileNotFoundException ex) {
      log.error("Error creating DOCX document", ex);
    } catch (IOException ex) {
      log.error("Error creating DOCX document", ex);
    } catch (Exception ex) {
      log.error("Error creating DOCX document", ex);
    }
  }
  public static void main(String[] args) throws Exception {

    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
    MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
    CTSettings ct = new CTSettings();
    DocumentSettingsPart dsp = documentPart.getDocumentSettingsPart();
    if (dsp == null) {
      dsp = new DocumentSettingsPart();
      CTView ctView = Context.getWmlObjectFactory().createCTView();
      ctView.setVal(STView.PRINT);
      ct.setView(ctView);
      BooleanDefaultTrue b = new BooleanDefaultTrue();
      b.setVal(true);
      ct.setUpdateFields(b);
      dsp.setJaxbElement(ct);
      documentPart.addTargetPart(dsp);
    }

    org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart.getJaxbElement();
    Body body = wmlDocumentEl.getBody();

    ObjectFactory factory = Context.getWmlObjectFactory();

    /*
     * Create the following:
     *
     * <w:p> <w:r> <w:fldChar w:dirty="true" w:fldCharType="begin"/>
     * <w:instrText xml:space="preserve">TOC \o &quot;1-3&quot; \h \z \ u
     * \h</w:instrText> </w:r> <w:r/> <w:r> <w:fldChar w:fldCharType="end"/>
     * </w:r> </w:p>
     */
    P paragraphForTOC = factory.createP();
    R r = factory.createR();

    FldChar fldchar = factory.createFldChar();
    fldchar.setFldCharType(STFldCharType.BEGIN);
    fldchar.setDirty(true);
    r.getContent().add(getWrappedFldChar(fldchar));
    paragraphForTOC.getContent().add(r);

    R r1 = factory.createR();
    Text txt = new Text();
    txt.setSpace("preserve");
    txt.setValue("TOC \\o \"1-3\" \\h \\z \\u ");
    r.getContent().add(factory.createRInstrText(txt));
    paragraphForTOC.getContent().add(r1);

    FldChar fldcharend = factory.createFldChar();
    fldcharend.setFldCharType(STFldCharType.END);
    R r2 = factory.createR();
    r2.getContent().add(getWrappedFldChar(fldcharend));
    paragraphForTOC.getContent().add(r2);

    body.getContent().add(paragraphForTOC);

    documentPart.addStyledParagraphOfText("Heading1", "Hello 1");
    documentPart.addStyledParagraphOfText("Heading2", "Hello 2");
    documentPart.addStyledParagraphOfText("Heading3", "Hello 3");
    documentPart.addStyledParagraphOfText("Heading1", "Hello 1");

    wordMLPackage.save(
        new java.io.File(System.getProperty("user.dir") + "/OUT_TableOfContentsAdd.docx"));
  }
Example #9
0
 /**
  * Sets the text of the given run to the given value.
  *
  * @param run the run whose text to change.
  * @param text the text to set.
  */
 public static void setText(R run, String text) {
   run.getContent().clear();
   Text textObj = factory.createText();
   textObj.setValue(text);
   run.getContent().add(textObj);
 }