/**
   * Creates a new empty abstract list.
   *
   * @return
   * @throws JAXBException
   */
  protected Numbering.AbstractNum createNewAbstractList() {

    // Create object for abstractNum
    Numbering.AbstractNum numberingabstractnum =
        Context.getWmlObjectFactory().createNumberingAbstractNum();
    //	    numbering.getAbstractNum().add( numberingabstractnum);
    numberingabstractnum.setAbstractNumId(BigInteger.valueOf(0));

    //	        // Create object for nsid
    //	        CTLongHexNumber longhexnumber =
    // Context.getWmlObjectFactory().createCTLongHexNumber();
    //	        numberingabstractnum.setNsid(longhexnumber);
    //	            longhexnumber.setVal( "3DEB26AB");

    // Create object for multiLevelType
    Numbering.AbstractNum.MultiLevelType numberingabstractnummultileveltype =
        Context.getWmlObjectFactory().createNumberingAbstractNumMultiLevelType();
    numberingabstractnum.setMultiLevelType(numberingabstractnummultileveltype);
    numberingabstractnummultileveltype.setVal("multilevel");

    //	        // Create object for tmpl
    //	        CTLongHexNumber longhexnumber2 =
    // Context.getWmlObjectFactory().createCTLongHexNumber();
    //	        numberingabstractnum.setTmpl(longhexnumber2);
    //	            longhexnumber2.setVal( "0C090023");

    return numberingabstractnum;
  }
Esempio n. 2
0
  private static SdtBlock createSdt(String tagVal, RPr rPr) {

    // .. so create content control!
    SdtBlock sdtBlock = Context.getWmlObjectFactory().createSdtBlock();

    SdtPr sdtPr = Context.getWmlObjectFactory().createSdtPr();
    sdtBlock.setSdtPr(sdtPr);

    SdtContentBlock sdtContent = Context.getWmlObjectFactory().createSdtContentBlock();
    sdtBlock.setSdtContent(sdtContent);

    // For borders/shading, we'll use the values in this first paragraph.
    // We'll use a tag, so the XSLT can detect that its supposed to do something special.
    Tag tag = Context.getWmlObjectFactory().createTag();
    tag.setVal(tagVal);

    sdtPr.setTag(tag);
    if (rPr != null) {
      sdtPr.getRPrOrAliasOrLock().add((RPr) XmlUtils.deepCopy(rPr));
      /*
       * ECMA-376 says "specifies the set of run properties which shall be applied to
       *  the text entered into the parent structured document tag in replacement of
       *  placeholder text. When placeholder text is present in a structured document
       *  tag, its formatting is often different than the desired underlying formatting,
       *  and this element specifies the formatting which shall be used for non-placeholder
       *  text contents when they are initially added to the control. "
       *
       * Note that docx2fo.xslt is co-opting this to do something else.
       */
    }
    return sdtBlock;
  }
Esempio n. 3
0
  /**
   * Convenience method to getJaxbElement().getBody().getContent()
   *
   * @since 2.7
   */
  public List<Object> getContent() {

    if (this.getJaxbElement() == null) {
      this.setJaxbElement(Context.getWmlObjectFactory().createDocument());
    }
    if (this.getJaxbElement().getBody() == null) {
      this.getJaxbElement().setBody(Context.getWmlObjectFactory().createBody());
    }

    return this.getJaxbElement().getContent();
  }
  @Override
  protected void exportCell(
      String bandName,
      BandElement bandElement,
      Object value,
      int gridRow,
      int row,
      int column,
      int cols,
      int rowSpan,
      int colSpan,
      boolean isImage) {

    if (newRow) {
      // rowNo for a table (it is reset in createTable)
      rowNo++;

      // for first row in page header and page footer we do not add the table row because it will be
      // duplicated
      if (((!ReportLayout.PAGE_HEADER_BAND_NAME.equals(bandName)
              && !ReportLayout.PAGE_FOOTER_BAND_NAME.equals(bandName)))
          || (rowNo > 1)) {
        if (tableRow != null) {
          if (ReportLayout.PAGE_HEADER_BAND_NAME.equals(bandName)) {
            tableHeader.getContent().add(tableRow);
          } else if (ReportLayout.PAGE_FOOTER_BAND_NAME.equals(bandName)) {
            tableFooter.getContent().add(tableRow);
          } else {
            table.getContent().add(tableRow);
          }
        }
        tableRow = factory.createTr();
      }
      // create table header to be available on every page
      if (bean.getReportLayout().isHeaderOnEveryPage()) {
        if (ReportLayout.HEADER_BAND_NAME.equals(bandName)) {
          TrPr rowProperties = new TrPr();
          BooleanDefaultTrue bdt = Context.getWmlObjectFactory().createBooleanDefaultTrue();
          rowProperties
              .getCnfStyleOrDivIdOrGridBefore()
              .add(Context.getWmlObjectFactory().createCTTrPrBaseTblHeader(bdt));
          tableRow.setTrPr(rowProperties);
        }
      }
    }

    renderDocxCell(bandName, bandElement, value, gridRow, rowSpan, colSpan, isImage, column);
  }
  /**
   * Compose an effective indent value.
   *
   * @param pPrDirectIndent
   * @param numberingIndent
   */
  public Indent(Ind pPrDirectIndent, Ind numberingIndent) {

    Ind val = Context.getWmlObjectFactory().createPPrBaseInd();
    if (pPrDirectIndent != null) {
      StyleUtil.apply(pPrDirectIndent, val);
    }
    if (numberingIndent != null) {
      // Use anything not specifically set already

      if (val.getHanging() == null
          && val.getFirstLine() == null // since these are mutually exclusive
          && numberingIndent.getHanging() != null) {
        val.setHanging(numberingIndent.getHanging());
      }
      if (val.getFirstLine() == null && numberingIndent.getFirstLine() != null) {
        val.setFirstLine(numberingIndent.getFirstLine());
      }

      if (val.getLeft() == null && numberingIndent.getLeft() != null) {
        val.setLeft(numberingIndent.getLeft());
      }
    }

    this.setObject(val);
  }
Esempio n. 6
0
  public PShading(CSSValue value) {

    CTShd shd = Context.getWmlObjectFactory().createCTShd();

    // PrimitiveType 25 -> RGBCOLOR
    short ignored = 1;

    float fRed;
    float fGreen;
    float fBlue;

    CSSPrimitiveValue cssPrimitiveValue = (CSSPrimitiveValue) value;
    try {
      fRed = cssPrimitiveValue.getRGBColorValue().getRed().getFloatValue(ignored);
      fGreen = cssPrimitiveValue.getRGBColorValue().getGreen().getFloatValue(ignored);
      fBlue = cssPrimitiveValue.getRGBColorValue().getBlue().getFloatValue(ignored);
      shd.setFill(UnitsOfMeasurement.rgbTripleToHex(fRed, fGreen, fBlue));

    } catch (UnsupportedOperationException e) {

      try {
        Class<?> xhtmlImporterClass =
            Class.forName("org.docx4j.convert.in.xhtml.FSColorToHexString");
        Method rgbToHexMethod = xhtmlImporterClass.getMethod("rgbToHex", CSSPrimitiveValue.class);
        shd.setFill((String) rgbToHexMethod.invoke(null, cssPrimitiveValue));
      } catch (Exception e2) {
        log.error("docx4j-XHTMLImport jar not found. Please add this to your classpath.");
        log.error(e2.getMessage(), e2);
        throw e; // same as before
      }
    }

    this.setObject(shd);
  }
Esempio n. 7
0
  public Style getEffectiveTableStyle(TblPr tblPr) {
    // OK to pass this a null tblPr.

    Stack<Style> tableStyleStack = new Stack<Style>();

    if (tblPr != null && tblPr.getTblStyle() != null) {
      String styleId = tblPr.getTblStyle().getVal();
      log.debug("Table style: " + styleId);
      fillTableStyleStack(styleId, tableStyleStack);
    } else {
      log.debug("No table style specified");
    }

    Style result;
    if (tableStyleStack.size() > 0) {
      result = XmlUtils.deepCopy(tableStyleStack.pop());
    } else {
      result = Context.getWmlObjectFactory().createStyle();
      if (tblPr == null) {
        // Return empty style object
        return result;
      }
    }
    while (!tableStyleStack.empty()) {
      StyleUtil.apply(tableStyleStack.pop(), result);
    }

    // Finally apply the tblPr we were passed
    result.setTblPr(StyleUtil.apply(tblPr, result.getTblPr()));

    return result;
  }
Esempio n. 8
0
  /**
   * Nastaví záhlaví dokumentu. Úprava předchozí funkce.
   *
   * @param irPackage
   * @throws InvalidFormatException
   */
  private Ftr SetupFooter(WordprocessingMLPackage irPackage) throws InvalidFormatException {
    ObjectFactory lrFactory = Context.getWmlObjectFactory();

    /* create header part */
    FooterPart lrFooterPart = new FooterPart();
    lrFooterPart.setPackage(irPackage);

    Ftr lrFooter = lrFactory.createFtr();

    lrFooterPart.setJaxbElement(lrFooter);
    Relationship lrRelationship = irPackage.getMainDocumentPart().addTargetPart(lrFooterPart);
    /* end create header part */

    /* create header reference */
    List<SectionWrapper> lrSections = irPackage.getDocumentModel().getSections();
    SectPr lrSectionPr = lrSections.get(lrSections.size() - 1).getSectPr();
    // There is always a section wrapper, but it might not contain a sectPr
    if (lrSectionPr == null) {
      lrSectionPr = lrFactory.createSectPr();
      irPackage.getMainDocumentPart().addObject(lrSectionPr);
      lrSections.get(lrSections.size() - 1).setSectPr(lrSectionPr);
    }

    FooterReference lrFooterReference = lrFactory.createFooterReference();
    lrFooterReference.setId(lrRelationship.getId());
    lrFooterReference.setType(HdrFtrRef.DEFAULT);
    lrSectionPr.getEGHdrFtrReferences().add(lrFooterReference); // add header or footer references
    /* end create header reference */

    return lrFooter;
  }
Esempio n. 9
0
 public WordDocument createOutputWorkbook(File f)
     throws InvalidFormatException, BadExtensionException, JAXBException {
   String filename = f.getName();
   switch (EXTENSIONS.getExtension(filename)) {
     case DOCX:
       {
         WordprocessingMLPackage pcg = WordprocessingMLPackage.createPackage();
         ObjectFactory of = Context.getWmlObjectFactory();
         Body b = pcg.getMainDocumentPart().getJaxbElement().getBody();
         Hdr lrHeader = SetupHeader(pcg);
         Ftr lrFooter = SetupFooter(pcg);
         SetupNumbering(pcg);
         WordDocument ret = new WordDocument(of, b, pcg, lrHeader, lrFooter);
         return ret;
       }
     case NONE:
       {
       }
     default:
       {
         throw new BadExtensionException(
             String.format("The filename %s is not acceptable for Excell Files", f.getName()));
       }
   }
 }
Esempio n. 10
0
  public void makeContinuous(SectPr sectPr) {

    if (sectPr == null) {
      log.warn("sectPr was null");
      return;
    }

    SectPr.Type type = Context.getWmlObjectFactory().createSectPrType();
    type.setVal("continuous");
    sectPr.setType(type);

    // columns, endnotes, footnotes, formprot, line numbers are OK

    // null out certain page level section properties
    sectPr.setBidi(null);
    sectPr.setDocGrid(null);
    sectPr.setPaperSrc(null);
    sectPr.setPgBorders(null);
    sectPr.setPgMar(null);
    sectPr.setPgNumType(null);
    sectPr.setPgSz(null);
    sectPr.setPrinterSettings(null);
    sectPr.setSectPrChange(null);
    sectPr.setTitlePg(null);
    sectPr.setVAlign(null);
  }
Esempio n. 11
0
 protected Property createShading(int fgColor, int bgColor, int pctFg) {
   CTShd shd = null;
   Shading ret = null;
   int resColor = UnitsOfMeasurement.combineColors(fgColor, bgColor, pctFg);
   String hResColor = UnitsOfMeasurement.toHexColor(resColor);
   shd = Context.getWmlObjectFactory().createCTShd();
   shd.setVal(STShd.CLEAR);
   shd.setFill(calcHexColor(resColor));
   return new Shading(shd);
 }
Esempio n. 12
0
 protected void appendNoneBordersAndShading(List<Property> tableProperties) {
   CTBorder ctBrdr = null;
   CTShd shd = Context.getWmlObjectFactory().createCTShd();
   ctBrdr = Context.getWmlObjectFactory().createCTBorder();
   ctBrdr.setVal(STBorder.NONE);
   tableProperties.add(new BorderLeft(ctBrdr));
   ctBrdr = Context.getWmlObjectFactory().createCTBorder();
   ctBrdr.setVal(STBorder.NONE);
   tableProperties.add(new BorderRight(ctBrdr));
   ctBrdr = Context.getWmlObjectFactory().createCTBorder();
   ctBrdr.setVal(STBorder.NONE);
   tableProperties.add(new BorderTop(ctBrdr));
   ctBrdr = Context.getWmlObjectFactory().createCTBorder();
   ctBrdr.setVal(STBorder.NONE);
   tableProperties.add(new BorderBottom(ctBrdr));
   shd.setColor("auto");
   shd.setFill("auto");
   shd.setVal(STShd.CLEAR);
   tableProperties.add(new Shading(shd));
 }
  protected Ind getInd(int twip) {

    Ind ind = Context.getWmlObjectFactory().createPPrBaseInd();

    //		ind.setLeft(BigInteger.valueOf(twip) );

    // Hanging hack
    ind.setLeft(BigInteger.valueOf(twip + 360));
    ind.setHanging(BigInteger.valueOf(360));
    return ind;
  }
  protected void setNumbering(PPr pPr, BigInteger numId) {

    // Create and add <w:numPr>
    NumPr numPr = Context.getWmlObjectFactory().createPPrBaseNumPr();
    pPr.setNumPr(numPr);

    // The <w:numId> element
    NumId numIdElement = Context.getWmlObjectFactory().createPPrBaseNumPrNumId();
    numPr.setNumId(numIdElement);
    numIdElement.setVal(numId); // point to the correct list

    // The <w:ilvl> element
    Ilvl ilvlElement = Context.getWmlObjectFactory().createPPrBaseNumPrIlvl();
    numPr.setIlvl(ilvlElement);
    ilvlElement.setVal(BigInteger.valueOf(this.listStack.size() - 1));

    // TMP: don't let this override our numbering
    //	    p.getPPr().setInd(null);

  }
Esempio n. 15
0
  /**
   * Follow the resolution rules to return the paragraph properties which actually apply, given this
   * pPr element (on a w:p).
   *
   * <p>Note 1: the properties are not the definition of any style name returned. Note 2: run
   * properties are not resolved or returned by this method.
   *
   * <p>What is returned is a live object. If you want to change it, you should clone it first!
   *
   * @param expressPPr
   * @return
   */
  public PPr getEffectivePPr(PPr expressPPr) {

    PPr effectivePPr = null;
    //	First, the document defaults are applied

    // Done elsewhere
    // PPr effectivePPr = (PPr)XmlUtils.deepCopy(documentDefaultPPr);

    //	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.
    PPr resolvedPPr = null;
    String styleId;
    if (expressPPr == null || expressPPr.getPStyle() == null) {
      //			styleId = "Normal";
      styleId = defaultParagraphStyleId;

    } else {
      styleId = expressPPr.getPStyle().getVal();
    }
    resolvedPPr = getEffectivePPr(styleId);

    //	Next, run properties are applied to each run with a specific character style
    //	applied.

    // Not for pPr

    //	Finally, we apply direct formatting (paragraph or run properties not from
    //	styles).
    if (hasDirectPPrFormatting(expressPPr)) {
      if (resolvedPPr == null) {
        log.warn("resolvedPPr was null. Look into this?");
        effectivePPr = Context.getWmlObjectFactory().createPPr();
      } else {
        effectivePPr = (PPr) XmlUtils.deepCopy(resolvedPPr);
      }
      applyPPr(expressPPr, effectivePPr);
      return effectivePPr;
    } else {
      return resolvedPPr;
    }
  }
  public Indent(CSSValue value) {

    debug(CSS_NAME, value);

    Ind ind = Context.getWmlObjectFactory().createPPrBaseInd();

    CSSPrimitiveValue cssPrimitiveValue = (CSSPrimitiveValue) value;

    int twip = getTwip(cssPrimitiveValue);
    ind.setLeft(BigInteger.valueOf(twip));
    this.setObject(ind);
  }
Esempio n. 17
0
public class RunUtil {

  private static ObjectFactory factory = Context.getWmlObjectFactory();

  private RunUtil() {}

  /**
   * Returns the text string of a run.
   *
   * @param run the run whose text to get.
   * @return String representation of the run.
   */
  public static String getText(R run) {
    String result = "";
    for (Object content : run.getContent()) {
      if (content instanceof JAXBElement) {
        JAXBElement element = (JAXBElement) content;
        if (element.getValue() instanceof Text) {
          result += ((Text) element.getValue()).getValue();
        }
      } else if (content instanceof Text) {
        result += ((Text) content).getValue();
      }
    }
    return result;
  }

  /**
   * 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);
  }

  /**
   * Creates a new run with the specified text.
   *
   * @param text the initial text of the run.
   * @return the newly created run.
   */
  public static R create(String text) {
    R run = factory.createR();
    setText(run, text);
    return run;
  }
}
Esempio n. 18
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;
  }
Esempio n. 19
0
  /**
   * Create a paragraph containing the string simpleText, styled using the specified style (up to
   * user to ensure it is a paragraph style) without adding it to the document.
   *
   * @param styleId
   * @param text
   * @return
   */
  public org.docx4j.wml.P createStyledParagraphOfText(String styleId, String text) {

    org.docx4j.wml.P p = createParagraphOfText(text);

    StyleDefinitionsPart styleDefinitionsPart = this.getStyleDefinitionsPart();

    if (getPropertyResolver().activateStyle(styleId)) {
      // Style is available
      org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
      org.docx4j.wml.PPr pPr = factory.createPPr();
      p.setPPr(pPr);
      org.docx4j.wml.PPrBase.PStyle pStyle = factory.createPPrBasePStyle();
      pPr.setPStyle(pStyle);
      pStyle.setVal(styleId);
    }

    return p;
  }
 @Override
 protected void initExport() throws QueryException {
   try {
     factory = Context.getWmlObjectFactory();
     for (int i = 0; i < bean.getReportLayout().getColumnCount(); i++) {
       rowSpanForColumn.put(i, 1);
     }
     if (!bean.isSubreport()) {
       boolean landscape = (bean.getReportLayout().getOrientation() == LANDSCAPE);
       wordMLPackage = WordprocessingMLPackage.createPackage(PageSizePaper.A4, landscape);
       setPageMargins();
       addMetadata();
     }
     table = createTable(PRINT_DOCUMENT);
   } catch (InvalidFormatException e) {
     e.printStackTrace();
     throw new QueryException(e);
   }
 }
 public P newImage(
     WordprocessingMLPackage wordMLPackage,
     byte[] bytes,
     String filenameHint,
     String altText,
     int id1,
     int id2,
     long cx)
     throws Exception {
   BinaryPartAbstractImage imagePart =
       BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
   Inline inline = imagePart.createImageInline(filenameHint, altText, id1, id2, cx, false);
   // Now add the inline in w:p/w:r/w:drawing
   ObjectFactory factory = Context.getWmlObjectFactory();
   P p = createParagraph();
   R run = factory.createR();
   p.getContent().add(run);
   Drawing drawing = factory.createDrawing();
   run.getContent().add(drawing);
   drawing.getAnchorOrInline().add(inline);
   return p;
 }
  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;
    }
  }
Esempio n. 23
0
  public static WordprocessingMLPackage createPackage(PageSizePaper sz, boolean landscape)
      throws InvalidFormatException {

    // Create a package
    WordprocessingMLPackage wmlPack = new WordprocessingMLPackage();

    // Create main document part
    MainDocumentPart wordDocumentPart = new MainDocumentPart();

    // Create main document part content
    org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
    org.docx4j.wml.Body body = factory.createBody();
    org.docx4j.wml.Document wmlDocumentEl = factory.createDocument();

    wmlDocumentEl.setBody(body);

    // Create a basic sectPr using our Page model
    PageDimensions page = new PageDimensions();
    page.setPgSize(sz, landscape);

    SectPr sectPr = factory.createSectPr();
    body.setSectPr(sectPr);
    sectPr.setPgSz(page.getPgSz());
    sectPr.setPgMar(page.getPgMar());

    // Put the content in the part
    wordDocumentPart.setJaxbElement(wmlDocumentEl);

    // Add the main document part to the package relationships
    // (creating it if necessary)
    wmlPack.addTargetPart(wordDocumentPart);

    // Create a styles part
    Part stylesPart = new org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart();
    try {
      ((org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart) stylesPart)
          .unmarshalDefaultStyles();

      // Add the styles part to the main document part relationships
      // (creating it if necessary)
      wordDocumentPart.addTargetPart(stylesPart); // NB - add it to main doc part, not package!		

    } catch (Exception e) {
      // TODO: handle exception
      // e.printStackTrace();
      log.error(e.getMessage(), e);
    }

    // Metadata: docx4j 2.7.1 can populate some of this from docx4j.properties
    // See SaveToZipFile
    DocPropsCorePart core = new DocPropsCorePart();
    org.docx4j.docProps.core.ObjectFactory coreFactory =
        new org.docx4j.docProps.core.ObjectFactory();
    core.setJaxbElement(coreFactory.createCoreProperties());
    wmlPack.addTargetPart(core);

    DocPropsExtendedPart app = new DocPropsExtendedPart();
    org.docx4j.docProps.extended.ObjectFactory extFactory =
        new org.docx4j.docProps.extended.ObjectFactory();
    app.setJaxbElement(extFactory.createProperties());
    wmlPack.addTargetPart(app);

    // Return the new package
    return wmlPack;
  }
  /**
   * Generates, saves, and opens Word template comments sheet based on a DocInfo object. It
   * generates a header table with course info stored in the DocInfo object. Each evaluation
   * question has its own table below the header table. The file is saved at the location specified
   * with a name generated by the program based on the course info.
   */
  public void generateCommentTemplate(DocInfo info, File saveLoc) {
    try {
      // Check if file exists. If it does exist, give the user the option
      // to cancel.
      File wordDoc = new File(saveLoc, generateSaveFileName(info));
      if (wordDoc.exists()) {
        String message =
            "The comment template sheet already exists. By selecting "
                + "yes, the file will be overwritten. Are you sure you want to overwrite "
                + "the file?";
        int response = JOptionPane.showConfirmDialog(null, message);
        if (response != JOptionPane.YES_OPTION) {
          return;
        }
      }

      wordMLPackage = WordprocessingMLPackage.createPackage();
      factory = Context.getWmlObjectFactory();

      // Add title to top of document
      wordMLPackage.getMainDocumentPart().addParagraphOfText("Student Feedback to Instructor");

      // Create table for header information
      Tbl courseInfoTable = factory.createTbl();

      // Create instructor name row
      Tr instNameRow = factory.createTr();
      addStyledTableCellWithWidth(
          instNameRow, "Instructor Name:", true, "20", TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          instNameRow,
          info.getInstFName() + " " + info.getInstLName(),
          false,
          "20",
          TABLE_LONG_FIELD_LENGTH);

      // Create subject/course number row
      Tr courseInfoRow = factory.createTr();
      addStyledTableCellWithWidth(courseInfoRow, "Course Subject & Number:", true, "20", 3000);
      addStyledTableCellWithWidth(
          courseInfoRow,
          info.getSubject() + " " + info.getCourseNum(),
          false,
          "20",
          TABLE_LONG_FIELD_LENGTH);

      // Create section row
      Tr sectionRow = factory.createTr();
      addStyledTableCellWithWidth(sectionRow, "Section:", true, "20", TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          sectionRow, info.getSection(), false, "20", TABLE_LONG_FIELD_LENGTH);

      // Semester/Year row
      Tr semesterRow = factory.createTr();
      addStyledTableCellWithWidth(semesterRow, "Semester:", true, "20", TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          semesterRow,
          info.getSemester().toString() + " " + info.getYear(),
          false,
          "20",
          TABLE_LONG_FIELD_LENGTH);

      // Add rows to table
      courseInfoTable.getContent().add(instNameRow);
      courseInfoTable.getContent().add(courseInfoRow);
      courseInfoTable.getContent().add(sectionRow);
      courseInfoTable.getContent().add(semesterRow);

      // Add border around entire table
      addBorders(courseInfoTable);

      // Place tables on document
      wordMLPackage.getMainDocumentPart().addObject(courseInfoTable);

      // Create a new table for each evaluation question
      for (String question : evalQuestions) {
        // Add empty paragraph so there is a space between questions
        wordMLPackage.getMainDocumentPart().addParagraphOfText(NEW_LINE);

        // Create table and add to doc
        Tbl questionTable = factory.createTbl();

        // Row with question
        Tr questionRow = factory.createTr();
        addStyledTableCellWithWidth(questionRow, question, true, "20", 10000);
        questionTable.getContent().add(questionRow);

        // Row with blank line for input
        Tr blankRow = factory.createTr();
        addStyledTableCellWithWidth(blankRow, "", true, "20", 10000);
        questionTable.getContent().add(blankRow);

        addBorders(questionTable);

        // Add table to document
        wordMLPackage.getMainDocumentPart().addObject(questionTable);
      }

      wordMLPackage.save(wordDoc);
      openFile(wordDoc);
    } catch (InvalidFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Docx4JException e) {
      JOptionPane.showMessageDialog(
          null,
          "The comment sheet could not be saved. Make sure the document is not already open in Word.");
      e.printStackTrace();
    }
  }
  /**
   * Generates an OIT scan sheet. If checkbox for print is open, uses a Desktop object to print to
   * the default printer. The current system date is used as the date.
   *
   * @param info Course inform
   * @param print If true, the document will be sent to default printer
   */
  public void generateOITSheet(DocInfo info, boolean print) {
    try {
      // Create new doc
      wordMLPackage = WordprocessingMLPackage.createPackage();
      factory = Context.getWmlObjectFactory();

      // Add title to top of document
      wordMLPackage.getMainDocumentPart().addParagraphOfText("OIT Scan Cover Sheet");

      // Create table for header information
      Tbl infoTable = factory.createTbl();

      // Create instructor name row
      Tr instNameRow = factory.createTr();
      addStyledTableCellWithWidth(
          instNameRow, "Instructor Name:", true, "20", TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          instNameRow,
          info.getInstFName() + " " + info.getInstLName(),
          false,
          "20",
          TABLE_LONG_FIELD_LENGTH);

      // Create subject/course number row
      Tr courseInfoRow = factory.createTr();
      addStyledTableCellWithWidth(courseInfoRow, "Course Subject & Number:", true, "20", 3000);
      addStyledTableCellWithWidth(
          courseInfoRow,
          info.getSubject() + " " + info.getCourseNum(),
          false,
          "20",
          TABLE_LONG_FIELD_LENGTH);

      // Create section row
      Tr sectionRow = factory.createTr();
      addStyledTableCellWithWidth(sectionRow, "Section:", true, "20", TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          sectionRow, info.getSection(), false, "20", TABLE_LONG_FIELD_LENGTH);

      // Semester/Year row
      Tr semesterRow = factory.createTr();
      addStyledTableCellWithWidth(semesterRow, "Semester:", true, "20", TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          semesterRow,
          info.getSemester().toString() + " " + info.getYear(),
          false,
          "20",
          TABLE_LONG_FIELD_LENGTH);

      // Faculty supp name row
      Tr facSuppNameRow = factory.createTr();
      addStyledTableCellWithWidth(
          facSuppNameRow, "Faculty Support Name:", true, "20", TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          facSuppNameRow, info.getFacSuppName(), false, "20", TABLE_LONG_FIELD_LENGTH);

      // Faculty supp name row
      Tr facSuppExtenRow = factory.createTr();
      addStyledTableCellWithWidth(
          facSuppExtenRow, "Faculty Support Extension:", true, "20", TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          facSuppExtenRow, info.getFacSuppExten(), false, "20", TABLE_LONG_FIELD_LENGTH);

      // Mailbox row
      Tr mailboxRow = factory.createTr();
      addStyledTableCellWithWidth(
          mailboxRow,
          "I would like the results delivered to mailbox:",
          true,
          "20",
          TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          mailboxRow, info.getMailbox(), false, "20", TABLE_LONG_FIELD_LENGTH);

      Tr dateRow = factory.createTr();
      DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
      Date date = new Date();
      System.out.println(dateFormat.format(date));
      addStyledTableCellWithWidth(
          dateRow, "Date of Request:", true, "20", TABLE_SHORT_FIELD_LENGTH);
      addStyledTableCellWithWidth(
          dateRow, dateFormat.format(date), false, "20", TABLE_LONG_FIELD_LENGTH);

      // Add rows to table
      infoTable.getContent().add(instNameRow);
      infoTable.getContent().add(courseInfoRow);
      infoTable.getContent().add(sectionRow);
      infoTable.getContent().add(semesterRow);
      infoTable.getContent().add(facSuppNameRow);
      infoTable.getContent().add(facSuppExtenRow);
      infoTable.getContent().add(mailboxRow);
      infoTable.getContent().add(dateRow);

      // Add border around entire table
      addBorders(infoTable);

      // Place tables on document
      wordMLPackage.getMainDocumentPart().addObject(infoTable);

      // Save in project files
      wordMLPackage.save(new File(OIT_SCAN_SHEET_SAVE_LOC));

      // Print or open file based on user decision
      if (print) {
        desktop.print(new File(OIT_SCAN_SHEET_SAVE_LOC));
      } else {
        desktop.open(new File(OIT_SCAN_SHEET_SAVE_LOC));
      }

      System.out.println("OIT Scan sheet generated.");

    } catch (InvalidFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Docx4JException e) {
      // TODO Auto-generated catch block
      JOptionPane.showMessageDialog(
          null, "Unable to open the OIT scan sheet. Make sure the document is not open.");
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  protected static List<ConversionSectionWrapper> processComplete(
      WordprocessingMLPackage wmlPackage,
      Document document,
      RelationshipsPart rels,
      BooleanDefaultTrue evenAndOddHeaders,
      boolean dummyPageNumbering) {
    List<ConversionSectionWrapper> conversionSections = new ArrayList<ConversionSectionWrapper>();
    List<Object> sectionContent = new ArrayList<Object>();
    ConversionSectionWrapper currentSectionWrapper = null;
    HeaderFooterPolicy previousHF = null;
    int conversionSectionIndex = 0;

    // According to the ECMA-376 2ed, if type is not specified, read it as next page
    // However Word 2007 sometimes treats it as continuous, and sometimes doesn't??
    // 20130216 Review above comment: !  In the Word UI, the Word "continuous" is shown where it is
    // effective.
    // In the XML, it is stored in the next following sectPr.

    // First, remove content controls,
    // since the P could be in a content control.
    // (It is easier to remove content controls, than
    //  to make the code below TraversalUtil based)
    // RemovalHandler is an XSLT-based way of doing this,
    // but here we avoid introducing a dependency on
    // XSLT (Xalan) for PDF output.
    SdtBlockFinder sbr = new SdtBlockFinder();
    new TraversalUtil(document.getContent(), sbr);
    for (int i = sbr.sdtBlocks.size() - 1; i >= 0; i--) {
      // Have to process in reverse order
      // so that parentList is correct for nested sdt

      SdtBlock sdtBlock = sbr.sdtBlocks.get(i);
      List<Object> parentList = null;
      if (sdtBlock.getParent() instanceof ArrayList) {
        parentList = (ArrayList) sdtBlock.getParent();
      } else {
        log.error("Handle " + sdtBlock.getParent().getClass().getName());
      }
      int index = parentList.indexOf(sdtBlock);
      parentList.remove(index);
      parentList.addAll(index, sdtBlock.getSdtContent().getContent());
    }

    //		if (log.isDebugEnabled()) {
    //			log.debug(XmlUtils.marshaltoString(document, true, true));
    //		}

    // Make a list, so it is easy to look at the following sectPr,
    // which we need to do to handle continuous sections properly
    List<SectPr> sectPrs = new ArrayList<SectPr>();
    for (Object o : document.getBody().getContent()) {

      if (o instanceof org.docx4j.wml.P) {
        if (((org.docx4j.wml.P) o).getPPr() != null) {
          org.docx4j.wml.PPr ppr = ((org.docx4j.wml.P) o).getPPr();
          if (ppr.getSectPr() != null) {
            sectPrs.add(ppr.getSectPr());
          }
        }
      }
    }

    if (document.getBody().getSectPr() != null) {
      // usual case
      sectPrs.add(document.getBody().getSectPr());

    } else {
      log.debug("No body level sectPr in document");

      // OK if the last object is w:p and it contains a sectPr.
      List<Object> all = document.getBody().getContent();
      Object last = all.get(all.size() - 1);
      if (last instanceof P
          && ((P) last).getPPr() != null
          && ((P) last).getPPr().getSectPr() != null) {
        // ok
        log.debug(
            ".. but last p contains sectPr .. move it"); // so our assumption later about there
                                                         // being a following section is correct

        SectPr thisSectPr = ((P) last).getPPr().getSectPr();
        document.getBody().setSectPr(thisSectPr);
        ((P) last).getPPr().setSectPr(null);
        sectPrs.remove(thisSectPr);

      } else {
        document.getBody().setSectPr(Context.getWmlObjectFactory().createSectPr());
        sectPrs.add(document.getBody().getSectPr());
      }
    }

    int sectPrIndex = 0; // includes continuous ones
    for (Object o : document.getBody().getContent()) {

      if (o instanceof org.docx4j.wml.P) {

        if (((org.docx4j.wml.P) o).getPPr() != null) {

          org.docx4j.wml.PPr ppr = ((org.docx4j.wml.P) o).getPPr();
          if (ppr.getSectPr() != null) {

            // If the *following* section is continuous, don't add *this* section
            boolean ignoreThisSection = false;
            SectPr followingSectPr = sectPrs.get(++sectPrIndex);
            if (followingSectPr.getType() != null
                && followingSectPr.getType().getVal().equals("continuous")) {

              ignoreThisSection = true;

              // If the w:pgSz on the two sections differs,
              // then Word inserts a page break (ie doesn't treat it as continuous).
              // If no w:pgSz element is present, then Word defaults
              // (presumably to Legal? TODO CHECK. There is no default setting in the docx).
              // Word always inserts a w:pgSz element?

              PgSz pgSzThis = ppr.getSectPr().getPgSz();
              PgSz pgSzNext = followingSectPr.getPgSz();

              if (pgSzThis != null && pgSzNext != null) {

                if (pgSzThis.getH().compareTo(pgSzNext.getH()) != 0) {
                  ignoreThisSection = false;
                }
                if (pgSzThis.getW().compareTo(pgSzNext.getW()) != 0) {
                  ignoreThisSection = false;
                }

                // Orientation:default is portrait
                boolean portraitThis = true;
                if (pgSzThis.getOrient() != null) {
                  portraitThis = pgSzThis.getOrient().equals(STPageOrientation.PORTRAIT);
                }
                boolean portraitNext = true;
                if (pgSzNext.getOrient() != null) {
                  portraitNext = pgSzNext.getOrient().equals(STPageOrientation.PORTRAIT);
                }
                if (portraitThis != portraitNext) {
                  ignoreThisSection = false;
                }
              }
              // TODO: handle cases where one or both pgSz elements are missing,
              // or H or W is missing.
              // Treat pgSz element missing as Legal size?
            }

            if (ignoreThisSection) {
              // In case there are some headers/footers that get inherited by the next section
              previousHF =
                  new HeaderFooterPolicy(ppr.getSectPr(), previousHF, rels, evenAndOddHeaders);

            } else {
              currentSectionWrapper =
                  createSectionWrapper(
                      ppr.getSectPr(),
                      previousHF,
                      rels,
                      evenAndOddHeaders,
                      ++conversionSectionIndex,
                      sectionContent,
                      dummyPageNumbering);
              conversionSections.add(currentSectionWrapper);
              previousHF = currentSectionWrapper.getHeaderFooterPolicy();
              sectionContent = new ArrayList<Object>();
            }
          }
        }
      }
      sectionContent.add(o);
      //			System.out.println(XmlUtils.marshaltoString(o, true));
    }

    currentSectionWrapper =
        createSectionWrapper(
            document.getBody().getSectPr(),
            previousHF,
            rels,
            evenAndOddHeaders,
            ++conversionSectionIndex,
            sectionContent,
            dummyPageNumbering);
    conversionSections.add(currentSectionWrapper);
    return conversionSections;
  }
Esempio n. 27
0
  public HighlightColor(CSSValue value) {

    Highlight shd = Context.getWmlObjectFactory().createHighlight();
    shd.setVal(value.getCssText());
    this.setObject(shd);
  }
Esempio n. 28
0
  /* (non-Javadoc)
   * @see org.docx4j.model.Model#toJAXB()
   */
  @Override
  public Object toJAXB() {

    ObjectFactory factory = Context.getWmlObjectFactory();
    Tbl tbl = factory.createTbl();

    // <w:tblPr>
    TblPr tblPr = null;
    if (tblPr == null) {
      log.warn("tblPr is null");
      tblPr = factory.createTblPr();

      // Default to page width
      TblWidth tblWidth = factory.createTblWidth();
      tblWidth.setW(BigInteger.valueOf(DEFAULT_PAGE_WIDTH_TWIPS));
      // TODO: shouldn't hard code that.  Pass it in?
      tblWidth.setType("dxa"); // twips
      tblPr.setTblW(tblWidth);
    }
    tbl.setTblPr(tblPr);

    // <w:tblGrid>
    // This specifies the number of columns,
    // and also their width
    if (tblGrid == null) {
      log.warn("tblGrid is null");
      tblGrid = factory.createTblGrid();
      // Default to equal width
      int width = Math.round(tbl.getTblPr().getTblW().getW().floatValue() / getColCount());
      for (int i = 0; i < getColCount(); i++) {
        TblGridCol tblGridCol = factory.createTblGridCol();
        tblGridCol.setW(BigInteger.valueOf(width)); // twips
        tblGrid.getGridCol().add(tblGridCol);
      }
    }
    tbl.setTblGrid(tblGrid);

    // <w:tr>
    // we need a table row, even if every entry is just a vertical span,
    // so that is easy
    for (int i = 0; i < cells.size(); i++) {
      Tr tr = factory.createTr();
      tbl.getEGContentRowContent().add(tr);

      // populate the row
      for (int j = 0; j < getColCount(); j++) {
        Tc tc = factory.createTc();
        Cell cell = cells.get(i).get(j);
        if (cell == null) {
          // easy, nothing to do.
          // this is just an empty tc
          tr.getEGContentCellContent().add(tc);
        } else {
          if (cell.isDummy()) {
            // we need to determine whether this is a result of
            // a vertical merge or a horizontal merge
            if (j > 0
                && (cells.get(i).get(j - 1).isDummy() || cells.get(i).get(j - 1).colspan > 1)) {
              // Its a horizontal merge, so
              // just leave it out
            } else if (i > 0
                && (cells.get(i - 1).get(j).isDummy() || cells.get(i - 1).get(j).rowspan > 1)) {
              // Its a vertical merge
              TcPr tcPr = factory.createTcPr();
              VMerge vm = factory.createTcPrInnerVMerge();
              tcPr.setVMerge(vm);
              tc.setTcPr(tcPr);
              tr.getEGContentCellContent().add(tc);

              // Must have an empty paragraph
              P p = factory.createP();
              tc.getEGBlockLevelElts().add(p);
            } else {
              log.error("Encountered phantom dummy cell at (" + i + "," + j + ") ");
              log.debug(debugStr());
            }

          } else { // a real cell
            TcPr tcPr = factory.createTcPr();

            if (cell.colspan > 1) {
              // add <w:gridSpan>
              GridSpan gridSpan = factory.createTcPrInnerGridSpan();
              gridSpan.setVal(BigInteger.valueOf(cell.colspan));
              tcPr.setGridSpan(gridSpan);
              tc.setTcPr(tcPr);
            }
            if (cell.rowspan > 1) {
              // Its a vertical merge
              VMerge vm = factory.createTcPrInnerVMerge();
              vm.setVal("restart");
              tcPr.setVMerge(vm);
              tc.setTcPr(tcPr);
            }

            if (cell.colspan > 1 && cell.rowspan > 1) {
              log.warn("Both rowspan & colspan set; that will be interesting..");
            }

            tr.getEGContentCellContent().add(tc);

            // Add the cell content, if we have it.
            // We won't have compatible content if this model has
            // been created via XSLT for an outward bound conversion.
            // But in that case, this method isn't needed
            // because the developer started with the JAXB model.
            Node foreign = cell.getContent(); // eg a <td>
            for (int n = 0; n < foreign.getChildNodes().getLength(); n++) {
              Object o;
              try {
                o = XmlUtils.unmarshal(foreign.getChildNodes().item(n));
                tc.getEGBlockLevelElts().add(o);
              } catch (JAXBException e) {
                e.printStackTrace();
              }
            }
          }
        }
      }
    }

    return tbl;
  }
public class ListHelper {

  public static Logger log = LoggerFactory.getLogger(XHTMLImporterImpl.class);

  public ListHelper(NumberingDefinitionsPart ndp) {
    this.ndp = ndp;
  }

  // Commented out for now; See list.txt
  //	public static final String XHTML_AbstractNum_For_OL = "XHTML_AbstractNum_For_OL";
  //	public static final String XHTML_AbstractNum_For_UL = "XHTML_AbstractNum_For_UL";

  private ObjectFactory wmlObjectFactory = Context.getWmlObjectFactory();

  private NumberingDefinitionsPart ndp;

  private LinkedList<BlockBox> listStack = new LinkedList<BlockBox>();
  // These are the incoming ul and ol.
  // Generally, these will be BlockBox (display:inline or display:inline-block).
  // <ul style="display:inline"> hides them entirely..

  // The current list
  private Numbering.AbstractNum abstractList;
  private Numbering.Num concreteList;

  protected void pushListStack(BlockBox ca) {
    listStack.push(ca);
  }

  protected BlockBox popListStack() {
    BlockBox box = listStack.pop();
    if (listStack.size() == 0) {
      // We're not in a list any more
      concreteList = null;
    }
    return box;
  }

  protected BlockBox peekListStack() {
    return listStack.peek();
  }

  protected int getDepth() {
    return listStack.size();
  }

  /**
   * Creates a new empty abstract list.
   *
   * @return
   * @throws JAXBException
   */
  protected Numbering.AbstractNum createNewAbstractList() {

    // Create object for abstractNum
    Numbering.AbstractNum numberingabstractnum =
        Context.getWmlObjectFactory().createNumberingAbstractNum();
    //	    numbering.getAbstractNum().add( numberingabstractnum);
    numberingabstractnum.setAbstractNumId(BigInteger.valueOf(0));

    //	        // Create object for nsid
    //	        CTLongHexNumber longhexnumber =
    // Context.getWmlObjectFactory().createCTLongHexNumber();
    //	        numberingabstractnum.setNsid(longhexnumber);
    //	            longhexnumber.setVal( "3DEB26AB");

    // Create object for multiLevelType
    Numbering.AbstractNum.MultiLevelType numberingabstractnummultileveltype =
        Context.getWmlObjectFactory().createNumberingAbstractNumMultiLevelType();
    numberingabstractnum.setMultiLevelType(numberingabstractnummultileveltype);
    numberingabstractnummultileveltype.setVal("multilevel");

    //	        // Create object for tmpl
    //	        CTLongHexNumber longhexnumber2 =
    // Context.getWmlObjectFactory().createCTLongHexNumber();
    //	        numberingabstractnum.setTmpl(longhexnumber2);
    //	            longhexnumber2.setVal( "0C090023");

    return numberingabstractnum;
  }

  private Lvl getLevel(Numbering.AbstractNum theList, int level) {

    if (level > 8) level = 8;

    for (Lvl lvl : theList.getLvl()) {
      if (lvl.getIlvl().intValue() == level) return lvl;
    }
    return null;
  }

  private NumberFormat getNumberFormatFromCSSListStyleType(String listStyleType) {

    //  disc | circle | square |
    // decimal | decimal-leading-zero | lower-roman | upper-roman |
    // lower-greek | lower-latin | upper-latin | armenian | georgian |
    // lower-alpha | upper-alpha | none | inherit
    if (listStyleType.equals("disc")
        || listStyleType.equals("circle")
        || listStyleType.equals("square")) {
      return NumberFormat.BULLET;
    }

    if (listStyleType.equals("decimal")) return NumberFormat.DECIMAL;

    if (listStyleType.equals("decimal-leading-zero")) return NumberFormat.DECIMAL_ZERO;

    if (listStyleType.equals("lower-roman")) return NumberFormat.LOWER_ROMAN;
    if (listStyleType.equals("upper-roman")) return NumberFormat.UPPER_ROMAN;

    if (listStyleType.equals("lower-greek")) return NumberFormat.DECIMAL; // no match

    if (listStyleType.equals("lower-latin")) return NumberFormat.LOWER_LETTER;
    if (listStyleType.equals("upper-latin")) return NumberFormat.UPPER_LETTER;

    if (listStyleType.equals("armenian")) return NumberFormat.DECIMAL; // no match
    if (listStyleType.equals("georgian")) return NumberFormat.DECIMAL; // no match

    if (listStyleType.equals("lower-alpha")) return NumberFormat.LOWER_LETTER;
    if (listStyleType.equals("upper-alpha")) return NumberFormat.UPPER_LETTER;

    if (listStyleType.equals("none")) return NumberFormat.NONE;
    if (listStyleType.equals("inherit")) return NumberFormat.DECIMAL; // TODO FIXME -

    return NumberFormat.DECIMAL; // appropriate fallback?
  }

  private String getLvlTextFromCSSListStyleType(String listStyleType, int level) {

    if (listStyleType.equals("disc")) {
      return "";
    }
    if (listStyleType.equals("circle")) {
      return "o";
    }
    if (listStyleType.equals("square")) {
      return "";
    }

    return "%" + level;
  }

  private RFonts geRFontsForCSSListStyleType(String listStyleType) {
    RFonts rfonts = null;
    if (listStyleType.equals("disc")) {
      rfonts = wmlObjectFactory.createRFonts();
      rfonts.setAscii("Symbol");
      rfonts.setHint(org.docx4j.wml.STHint.DEFAULT);
      rfonts.setHAnsi("Symbol");
    }
    if (listStyleType.equals("circle")) {
      rfonts = wmlObjectFactory.createRFonts();
      rfonts.setAscii("Courier New");
      rfonts.setHint(org.docx4j.wml.STHint.DEFAULT);
      rfonts.setHAnsi("Courier New");
      rfonts.setCs("Courier New");
    }
    if (listStyleType.equals("square")) {
      rfonts = wmlObjectFactory.createRFonts();
      rfonts.setAscii("Wingdings");
      rfonts.setHint(org.docx4j.wml.STHint.DEFAULT);
      rfonts.setHAnsi("Wingdings");
    }
    return rfonts;
  }

  protected Ind getInd(int twip) {

    Ind ind = Context.getWmlObjectFactory().createPPrBaseInd();

    //		ind.setLeft(BigInteger.valueOf(twip) );

    // Hanging hack
    ind.setLeft(BigInteger.valueOf(twip + 360));
    ind.setHanging(BigInteger.valueOf(360));
    return ind;
  }

  protected int getAncestorIndentation() {

    // Indentation.  Sum of padding-left and margin-left on ancestor ol|ul
    // Expectation is that one or other would generally be used.
    int totalPadding = 0;
    for (BlockBox bb : listStack) {
      LengthValue padding = (LengthValue) bb.getStyle().valueByName(CSSName.PADDING_LEFT);
      totalPadding += Indent.getTwip(padding.getCSSPrimitiveValue());

      log.debug("+padding-left: " + totalPadding);

      LengthValue margin = (LengthValue) bb.getStyle().valueByName(CSSName.MARGIN_LEFT);
      totalPadding += Indent.getTwip(margin.getCSSPrimitiveValue());

      log.debug("+margin-left: " + totalPadding);
    }
    return totalPadding;
  }

  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;
  }

  void addNumbering(P p, Element e, Map<String, CSSValue> cssMap) {

    if (concreteList == null) {
      // We've just entered a list, so create a new one
      abstractList = createNewAbstractList();
      concreteList = ndp.addAbstractListNumberingDefinition(abstractList);
    }

    // Do we have a definition for this level yet?
    Lvl lvl = getLevel(abstractList, listStack.size() - 1);
    if (lvl == null) {
      // Nope, need to create it
      abstractList.getLvl().add(createLevel(listStack.size() - 1, cssMap));
    }

    setNumbering(p.getPPr(), concreteList.getNumId());
  }

  protected void setNumbering(PPr pPr, BigInteger numId) {

    // Create and add <w:numPr>
    NumPr numPr = Context.getWmlObjectFactory().createPPrBaseNumPr();
    pPr.setNumPr(numPr);

    // The <w:numId> element
    NumId numIdElement = Context.getWmlObjectFactory().createPPrBaseNumPrNumId();
    numPr.setNumId(numIdElement);
    numIdElement.setVal(numId); // point to the correct list

    // The <w:ilvl> element
    Ilvl ilvlElement = Context.getWmlObjectFactory().createPPrBaseNumPrIlvl();
    numPr.setIlvl(ilvlElement);
    ilvlElement.setVal(BigInteger.valueOf(this.listStack.size() - 1));

    // TMP: don't let this override our numbering
    //	    p.getPPr().setInd(null);

  }
}
Esempio n. 30
0
  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"));
  }