Example #1
0
  private static void appendRun(SdtBlock currentBlock, List<Object> resultElts) {

    List<Object> blkElements = null;
    R run = null;
    RPr blockRPr = null;
    if (currentBlock != null) {
      blkElements = currentBlock.getSdtContent().getContent();
      if (blkElements.size() == 1) {
        // If there is only one element, there is no need to use a sdtBlock
        resultElts.add(blkElements.get(0));
      } else {
        resultElts.add(currentBlock);
        // Remove the borders of the child elements
        // (and the shading if it is the same as that of the container)
        blockRPr = findBlockRPr(currentBlock);
        for (Object elem : blkElements) {
          if (elem instanceof R) {
            run = (R) elem;
            if (run.getRPr() != null) {
              run.getRPr().setBdr(null);
              if (!shadingChanged(blockRPr.getShd(), run.getRPr().getShd())) {
                run.getRPr().setShd(null);
              }
            }
          }
        }
      }
    }
  }
Example #2
0
  /**
   * Sets font style (bold/italic) for a paragraph run
   *
   * @param runElement Run
   * @param italic wheter to set italic style
   * @param bold wheter to set bold style
   */
  private void setFontStyle(R runElement, boolean italic, boolean bold) {
    RPr runProps = runElement.getRPr();
    if (null == runProps) runProps = objectFactory.createRPr();
    if (italic) runProps.setI(objectFactory.createBooleanDefaultTrue());
    if (bold) runProps.setB(objectFactory.createBooleanDefaultTrue());

    runElement.setRPr(runProps);
  }
 private void setFontSize(RPr runProperties, String fontSize) {
   if (fontSize != null && !fontSize.isEmpty()) {
     HpsMeasure size = new HpsMeasure();
     size.setVal(new BigInteger(fontSize));
     runProperties.setSz(size);
     runProperties.setSzCs(size);
   }
 }
 private void setFontFamily(RPr runProperties, String fontFamily) {
   if (fontFamily != null) {
     RFonts rf = runProperties.getRFonts();
     if (rf == null) {
       rf = new RFonts();
       runProperties.setRFonts(rf);
     }
     rf.setAscii(fontFamily);
   }
 }
  private Lvl createLevel(int level, Map<String, CSSValue> cssMap) {

    if (level > 8) level = 8; // Word can't open a document with Ilvl>8

    // Create object for lvl
    Lvl lvl = wmlObjectFactory.createLvl();
    lvl.setIlvl(BigInteger.valueOf(level));

    //            // Create object for pStyle
    //            Lvl.PStyle lvlpstyle = wmlObjectFactory.createLvlPStyle();
    //            lvl.setPStyle(lvlpstyle);
    //                lvlpstyle.setVal( "Heading1");

    // Create object for pPr
    PPr ppr = wmlObjectFactory.createPPr();
    lvl.setPPr(ppr);

    ppr.setInd(getInd(getAncestorIndentation()));

    // Create object for numFmt
    NumFmt numfmt = wmlObjectFactory.createNumFmt();
    lvl.setNumFmt(numfmt);
    numfmt.setVal(getNumberFormatFromCSSListStyleType(cssMap.get("list-style-type").getCssText()));

    // Create object for lvlText
    Lvl.LvlText lvllvltext = wmlObjectFactory.createLvlLvlText();
    lvl.setLvlText(lvllvltext);
    lvllvltext.setVal(
        getLvlTextFromCSSListStyleType(cssMap.get("list-style-type").getCssText(), level + 1));

    // Bullets have an associated font
    RFonts rfonts = geRFontsForCSSListStyleType(cssMap.get("list-style-type").getCssText());
    if (rfonts != null) {
      RPr rpr = wmlObjectFactory.createRPr();
      rpr.setRFonts(rfonts);
      lvl.setRPr(rpr);
    }

    // Create object for lvlJc
    Jc jc = wmlObjectFactory.createJc();
    lvl.setLvlJc(jc);
    jc.setVal(org.docx4j.wml.JcEnumeration.LEFT);

    // Create object for start
    Lvl.Start lvlstart = wmlObjectFactory.createLvlStart();
    lvl.setStart(lvlstart);
    lvlstart.setVal(BigInteger.valueOf(1));

    return lvl;
  }
 private void setFontColor(RPr runProperties, String color) {
   if (color != null) {
     org.docx4j.wml.Color c = new org.docx4j.wml.Color();
     c.setVal(color);
     runProperties.setColor(c);
   }
 }
Example #7
0
  /**
   * Returns default document font, by attempting to look at
   * styles/docDefaults/rPrDefault/rPr/rFonts.
   *
   * @return default document font.
   */
  public String getDefaultFont() {

    // First look at the defaults
    // 3 look at styles/rPrDefault
    //   eg <w:rFonts w:asciiTheme="minorHAnsi" w:eastAsiaTheme="minorEastAsia"
    //				  w:hAnsiTheme="minorHAnsi" w:cstheme="minorBidi"/>
    // 3.1 if there is an rFonts element, do what it says (it may refer you to the theme part,
    //     in which case if there is no theme part, default to "internally stored settings"
    //	   (there is no normal.dot; see http://support.microsoft.com/kb/924460/en-us )
    //	   in this case Calibri and Cambria)
    // 3.2 if there is no rFonts element, default to Times New Roman.

    org.docx4j.wml.RFonts rFonts = documentDefaultRPr.getRFonts();
    if (rFonts == null) {
      log.info("No styles/docDefaults/rPrDefault/rPr/rFonts - default to Times New Roman");
      // Yes, Times New Roman is still buried in Word 2007
      return "Times New Roman";
    } else {
      // Usual case
      if (rFonts.getAsciiTheme() != null) {
        // for example minorHAnsi, which I think translates to minorFont/latin
        if (rFonts.getAsciiTheme().equals(org.docx4j.wml.STTheme.MINOR_H_ANSI)) {
          if (themePart != null) {
            org.docx4j.dml.BaseStyles.FontScheme fontScheme = themePart.getFontScheme();
            if (fontScheme.getMinorFont() != null && fontScheme.getMinorFont().getLatin() != null) {

              org.docx4j.dml.TextFont textFont = fontScheme.getMinorFont().getLatin();
              log.debug("minorFont/latin font is " + textFont.getTypeface());
              return textFont.getTypeface();
            } else {
              // No minorFont/latin in theme part - default to Calibri
              log.info("No minorFont/latin in theme part - default to Calibri");
              return "Calibri";
            }
          } else {
            // No theme part - default to Calibri
            log.info("No theme part - default to Calibri");
            return "Calibri";
          }
        } else {
          // TODO
          log.error("Don't know how to handle: " + rFonts.getAsciiTheme());
          return null;
        }
      } else if (rFonts.getAscii() != null) {
        log.info("rPrDefault/rFonts referenced " + rFonts.getAscii());
        return rFonts.getAscii();
      } else {
        // TODO
        log.error("Neither ascii or asciTheme.  What to do? ");
        return null;
      }
    }
  }
  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;
    }
  }
  private P createPageNumParagraph() {
    CTSimpleField pgnum = factory.createCTSimpleField();
    pgnum.setInstr(" PAGE \\* MERGEFORMAT ");
    RPr RPr = factory.createRPr();
    RPr.setNoProof(new BooleanDefaultTrue());
    PPr ppr = factory.createPPr();
    Jc jc = factory.createJc();
    jc.setVal(JcEnumeration.CENTER);
    ppr.setJc(jc);
    PPrBase.Spacing pprbase = factory.createPPrBaseSpacing();
    pprbase.setBefore(BigInteger.valueOf(240));
    pprbase.setAfter(BigInteger.valueOf(0));
    ppr.setSpacing(pprbase);

    R run = factory.createR();
    run.getContent().add(RPr);
    pgnum.getContent().add(run);

    JAXBElement<CTSimpleField> fldSimple = factory.createPFldSimple(pgnum);
    P para = createParagraph();
    para.getContent().add(fldSimple);
    para.setPPr(ppr);
    return para;
  }
Example #10
0
  public String getDefaultFontEastAsia() {

    org.docx4j.wml.RFonts rFonts = documentDefaultRPr.getRFonts();
    if (rFonts == null) {
      log.info("No styles/docDefaults/rPrDefault/rPr/rFonts - default to SimSun");
      return "SimSun";
    } else {
      // Usual case

      if (rFonts.getEastAsiaTheme() != null) {
        // for example minorEastAsia
        if (rFonts.getEastAsiaTheme().equals(org.docx4j.wml.STTheme.MINOR_EAST_ASIA)) {
          if (themePart != null) {
            org.docx4j.dml.BaseStyles.FontScheme fontScheme = themePart.getFontScheme();
            if (fontScheme.getMinorFont() != null
                && fontScheme.getMinorFont().getEa() != null
                && !fontScheme.getMinorFont().getEa().getTypeface().equals("")) {

              log.debug("minorFont/EA font is " + fontScheme.getMinorFont().getEa().getTypeface());
              return fontScheme.getMinorFont().getEa().getTypeface();
            } else {
              // No minorFont/EA in theme part - default to SimSun
              log.info("No minorFont/latin in theme part - default to SimSun");
              return "SimSun";
            }
          } else {
            // No theme part - default to SimSun
            log.info("No theme part - default to SimSun");
            return "SimSun";
          }
        } else {
          // TODO
          log.error("Don't know how to handle: " + rFonts.getEastAsiaTheme());
          return null;
        }
      } else if (rFonts.getEastAsia() != null) {
        log.info("rPrDefault/rFonts referenced " + rFonts.getEastAsia());
        return rFonts.getEastAsia();
      } else {
        // TODO
        log.error("Neither EastAsia or EastAsiaTheme.  What to do? ");
        return null;
      }
    }
  }
Example #11
0
    @Override
    public List<Object> apply(Object o) {

      if (o instanceof org.docx4j.wml.P) {
        pPr = ((P) o).getPPr();
        if (stylesInUse != null) { // do the styles
          boolean customPStyle = false;
          if (pPr != null) {
            if (pPr.getPStyle() != null) {
              // Note this paragraph style
              // log.debug("put style " + pPr.getPStyle().getVal());
              customPStyle = true;
              stylesInUse.add(pPr.getPStyle().getVal());
            }
            if ((pPr.getRPr() != null) && (pPr.getRPr().getRStyle() != null)) {
              // 	Note this run style
              // log.debug("put style " + pPr.getRPr().getRStyle().getVal() );
              stylesInUse.add(pPr.getRPr().getRStyle().getVal());
            }
          }
          defaultParagraphStyleUsed = defaultParagraphStyleUsed || (!customPStyle);
        }

      } else if (o instanceof org.docx4j.wml.R) {
        rPr = ((R) o).getRPr();
        if (stylesInUse != null) {
          if (rPr != null) {
            if (rPr.getRStyle() == null) {
              defaultCharacterStyleUsed = true;
            } else {
              stylesInUse.add(rPr.getRStyle().getVal());
            }
          }
        }

      } else if (o instanceof org.docx4j.wml.Text) {

        if (runFontSelector != null) {
          // discover the fonts which apply to this text
          log.debug(((Text) o).getValue());
          runFontSelector.fontSelector(pPr, rPr, ((Text) o));
        }

      } else if (o instanceof org.docx4j.wml.R.Sym) {

        if (fontsDiscovered != null) {
          org.docx4j.wml.R.Sym sym = (org.docx4j.wml.R.Sym) o;
          fontsDiscovered.add(sym.getFont());
        }

      } else if (o instanceof org.docx4j.wml.Tbl) {
        // The table could have a table style;
        // Tables created in Word 2007 default to table style "TableGrid",
        // which is based on "TableNormal".
        org.docx4j.wml.Tbl tbl = (org.docx4j.wml.Tbl) o;
        if (stylesInUse != null && tbl.getTblPr() != null && tbl.getTblPr().getTblStyle() != null) {
          //					log.debug("Adding table style: " + tbl.getTblPr().getTblStyle().getVal() );
          stylesInUse.add(tbl.getTblPr().getTblStyle().getVal());
        }
        // There is no such thing as a tr or a tc style,
        // so we don't need to look for them,
        // but since a tc can contain w:p or nested table,
        // we still need to recurse

      }
      return null;
    }
Example #12
0
 @Override
 public void set(RPr rPr) {
   rPr.setHighlight((Highlight) this.getObject());
 }
Example #13
0
  private boolean hasDirectRPrFormatting(RPr rPrToApply) {

    if (rPrToApply == null) {
      return false;
    }

    // Here is where we do the real work.
    // There are a lot of run properties
    // The below list is taken directly from RPr, and so
    // is comprehensive.

    // RStyle rStyle;
    // RFonts rFonts;
    if (rPrToApply.getRFonts() != null) {
      return true;
    }

    // BooleanDefaultTrue b;
    if (rPrToApply.getB() != null) {
      return true;
    }

    // BooleanDefaultTrue bCs;
    // BooleanDefaultTrue i;
    if (rPrToApply.getI() != null) {
      return true;
    }

    // BooleanDefaultTrue iCs;
    // BooleanDefaultTrue caps;
    if (rPrToApply.getCaps() != null) {
      return true;
    }

    // BooleanDefaultTrue smallCaps;
    if (rPrToApply.getSmallCaps() != null) {
      return true;
    }

    // BooleanDefaultTrue strike;
    if (rPrToApply.getStrike() != null) {
      return true;
    }
    // BooleanDefaultTrue dstrike;
    // BooleanDefaultTrue outline;
    // BooleanDefaultTrue shadow;
    // BooleanDefaultTrue emboss;
    // BooleanDefaultTrue imprint;
    // BooleanDefaultTrue noProof;
    // BooleanDefaultTrue snapToGrid;
    // BooleanDefaultTrue vanish;
    // BooleanDefaultTrue webHidden;
    // Color color;
    if (rPrToApply.getColor() != null) {
      return true;
    }

    // CTSignedTwipsMeasure spacing;
    // CTTextScale w;
    // HpsMeasure kern;
    // CTSignedHpsMeasure position;
    // HpsMeasure sz;
    if (rPrToApply.getSz() != null) {
      return true;
    }

    // HpsMeasure szCs;
    // Highlight highlight;
    if (rPrToApply.getHighlight() != null) {
      return true;
    }
    // U u;
    if (rPrToApply.getU() != null) {
      return true;
    }

    // CTTextEffect effect;
    // CTBorder bdr;
    if (rPrToApply.getBdr() != null) {
      return true;
    }
    // CTShd shd;
    if (rPrToApply.getShd() != null) {
      return true;
    }
    // CTFitText fitText;
    // CTVerticalAlignRun vertAlign;
    // BooleanDefaultTrue rtl;
    // BooleanDefaultTrue cs;
    // CTEm em;
    // CTLanguage lang;
    // CTEastAsianLayout eastAsianLayout;
    // BooleanDefaultTrue specVanish;
    // BooleanDefaultTrue oMath;
    // CTRPrChange rPrChange;

    // If we got here...
    return false;
  }
Example #14
0
  /**
   * @param expressRPr
   * @param pPr -
   * @return
   */
  public RPr getEffectiveRPr(RPr expressRPr, PPr pPr) {

    // NB Currently used in PDF viaXSLFO only

    log.debug("in getEffectiveRPr");

    //		Idea is that you pass pPr if you are using this for XSL FO,
    //		since we need to take account of rPr in paragraph styles
    //		(but not the rPr in a pPr direct formatting, since
    //       that only applies to the paragraph mark).
    //		 * For HTML/CSS, this would be null (since the pPr level rPr
    //		 * is made into a separate style applied via a second value in
    //		 * the class attribute).  But, in the CSS case, this
    // function is not used - since the rPr is made into a style as well.

    //	First, the document defaults are applied

    RPr effectiveRPr = (RPr) XmlUtils.deepCopy(documentDefaultRPr);

    // Apply DefaultParagraphFont.  We only do it explicitly
    // here as per conditions, because if there is a run style,
    // walking the hierarchy will include this if it is needed
    if (expressRPr == null || expressRPr.getRStyle() == null) {
      applyRPr(resolvedStyleRPrComponent.get(defaultCharacterStyleId), effectiveRPr);
    }

    //	Next, the table style properties are applied to each table in the document,
    //	following the conditional formatting inclusions and exclusions specified
    //	per table.

    // TODO - if the paragraph is in a table?

    //	Next, numbered item and paragraph properties are applied to each paragraph
    //	formatted with a *numbering *style**.

    //			 TODO - who uses numbering styles (as opposed to numbering
    // via a paragraph style or direct formatting)?

    //  Next, paragraph and run properties are
    //	applied to each paragraph as defined by the paragraph style
    // (this includes run properties defined in a paragraph style,
    //  but not run properties directly included in a pPr in the
    //  document (those only apply to a paragraph mark).

    if (pPr == null) {
      log.debug("pPr was null");
    } else {
      // At the pPr level, what rPr do we have?
      // .. ascend the paragraph style tree
      if (pPr.getPStyle() == null) {
        //					log.warn("No pstyle:");
        //					log.debug(XmlUtils.marshaltoString(pPr, true, true));
      } else {
        log.debug("pstyle:" + pPr.getPStyle().getVal());
        RPr pPrLevelRunStyle = getEffectiveRPr(pPr.getPStyle().getVal());
        // .. and apply those
        applyRPr(pPrLevelRunStyle, effectiveRPr);
      }
      // Check Paragraph rPr (our special hack of using ParaRPr
      // to format a fo:block)
      if ((expressRPr == null)
          && (pPr.getRPr() != null)
          && (hasDirectRPrFormatting(pPr.getRPr()))) {
        applyRPr(pPr.getRPr(), effectiveRPr);
      }
    }
    //	Next, run properties are applied to each run with a specific character style
    //	applied.
    RPr resolvedRPr = null;
    String runStyleId;
    if (expressRPr != null && expressRPr.getRStyle() != null) {
      runStyleId = expressRPr.getRStyle().getVal();
      resolvedRPr = getEffectiveRPr(runStyleId);
      applyRPr(resolvedRPr, effectiveRPr);
    }

    //	Finally, we apply direct formatting (run properties not from
    //	styles).
    if (hasDirectRPrFormatting(expressRPr)) {
      // effectiveRPr = (RPr)XmlUtils.deepCopy(effectiveRPr);
      applyRPr(expressRPr, effectiveRPr);
    }
    return effectiveRPr;
  }
 private void addUnderlineStyle(RPr runProperties) {
   U val = new U();
   val.setVal(UnderlineEnumeration.SINGLE);
   runProperties.setU(val);
 }
Example #16
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);
    }
  }
Example #17
0
  /**
   * @return the font name, or null if there is no rFonts element in any style in the style
   *     inheritance hierarchy (ie this method does not look up
   *     styles/docDefaults/rPrDefault/rPr/rFonts or from there, the theme part).
   */
  public static String getFontnameFromStyle(
      Map stylesDefined, ThemePart themePart, org.docx4j.wml.Style style) {

    /*
    a paragraph style does not inherit anything from its linked character style.

    A linked character style seems to be just a Word 2007 user interface
    hint.  ie if you select some characters in a paragraph and select to
    apply "Heading 1", what you are actually doing is applying "Heading 1
    char".  This is determined by looking at the definition of the
    "Heading 1" style to see what its linked style is.

    (Interestingly, in Word 2007, if you right click to modify something
     which is Heading 1 char, it modifies both the Heading 1 style and the
     Heading 1 char style!.  Haven't looked to see what happens to Heading 1 char
     style if you right click to modify a Heading 1 par.)

     The algorithm Word 2007 seems to use is:
        look at the specified style:
            1 does it have its own rPr which contains rFonts?
            2 if not, what does this styles basedOn style say? (Ignore
    any linked char style)
    		3 look at styles/rPrDefault
    		3.1 if there is an rFonts element, do what it says (it may refer you to the theme part,
    		    in which case if there is no theme part, default to "internally stored settings"
    			(there is no normal.dot; see http://support.microsoft.com/kb/924460/en-us )
    			in this case Calibri and Cambria)
    		3.2 if there is no rFonts element, default to Times New Roman.


    For efficiency reasons, we don't do 3 in this method.
     */

    // 1 does it have its own rPr which contains rFonts?
    org.docx4j.wml.RPr rPr = style.getRPr();
    if (rPr != null && rPr.getRFonts() != null) {
      if (rPr.getRFonts().getAscii() != null) {
        return rPr.getRFonts().getAscii();
      } else if (rPr.getRFonts().getAsciiTheme() != null && themePart != null) {
        log.debug("Encountered rFonts/AsciiTheme: " + rPr.getRFonts().getAsciiTheme());

        org.docx4j.dml.Theme theme = (org.docx4j.dml.Theme) themePart.getJaxbElement();
        org.docx4j.dml.BaseStyles.FontScheme fontScheme = themePart.getFontScheme();
        if (rPr.getRFonts().getAsciiTheme().equals(org.docx4j.wml.STTheme.MINOR_H_ANSI)) {
          if (fontScheme != null && fontScheme.getMinorFont().getLatin() != null) {
            fontScheme = theme.getThemeElements().getFontScheme();
            org.docx4j.dml.TextFont textFont = fontScheme.getMinorFont().getLatin();
            log.info("minorFont/latin font is " + textFont.getTypeface());
            return (textFont.getTypeface());
          } else {
            // No minorFont/latin in theme part - default to Calibri
            log.info("No minorFont/latin in theme part - default to Calibri");
            return ("Calibri");
          }
        } else if (rPr.getRFonts().getAsciiTheme().equals(org.docx4j.wml.STTheme.MAJOR_H_ANSI)) {
          if (fontScheme != null && fontScheme.getMajorFont().getLatin() != null) {
            fontScheme = theme.getThemeElements().getFontScheme();
            org.docx4j.dml.TextFont textFont = fontScheme.getMajorFont().getLatin();
            log.debug("majorFont/latin font is " + textFont.getTypeface());
            return (textFont.getTypeface());
          } else {
            // No minorFont/latin in theme part - default to Cambria
            log.info("No majorFont/latin in theme part - default to Cambria");
            return ("Cambria");
          }
        } else {
          log.error("Don't know how to handle: " + rPr.getRFonts().getAsciiTheme());
        }
      }
    }

    // 2 if not, what does this styles basedOn style say? (recursive)

    if (style.getBasedOn() != null && style.getBasedOn().getVal() != null) {
      String basedOnStyleName = style.getBasedOn().getVal();
      // log.debug("recursing into basedOn:" + basedOnStyleName);
      org.docx4j.wml.Style candidateStyle =
          (org.docx4j.wml.Style) stylesDefined.get(basedOnStyleName);
      if (candidateStyle != null && candidateStyle.getStyleId().equals(basedOnStyleName)) {
        return getFontnameFromStyle(stylesDefined, themePart, candidateStyle);
      }
      // If we get here the style is missing!
      log.error("couldn't find basedOn:" + basedOnStyleName);
      return null;
    } else {
      // log.debug("No basedOn set for: " + style.getStyleId() );
      return null;
    }
  }
 private void addItalicStyle(RPr runProperties) {
   BooleanDefaultTrue b = new BooleanDefaultTrue();
   b.setVal(true);
   runProperties.setI(b);
 }