示例#1
0
 /**
  * Fills table cell with given hex color
  *
  * @param cell
  * @param hexColor
  */
 private void fillTableCell(Tc cell, String hexColor) {
   TcPr cellProps = cell.getTcPr();
   if (null == cellProps) cellProps = objectFactory.createTcPr();
   CTShd shd = objectFactory.createCTShd();
   shd.setFill(hexColor);
   shd.setThemeFill(STThemeColor.BACKGROUND_2);
   cellProps.setShd(shd);
   cell.setTcPr(cellProps);
 }
  private void setCellMargins(Tc tableCell, Map<String, Object> style) {
    int top = 0, left = 0, bottom = 0, right = 0;
    if (style.containsKey(StyleFormatConstants.PADDING_LEFT)) {
      Float val = (Float) style.get(StyleFormatConstants.PADDING_LEFT);
      left = val.intValue();
    }
    if (style.containsKey(StyleFormatConstants.PADDING_RIGHT)) {
      Float val = (Float) style.get(StyleFormatConstants.PADDING_RIGHT);
      right = val.intValue();
    }
    if (style.containsKey(StyleFormatConstants.PADDING_TOP)) {
      Float val = (Float) style.get(StyleFormatConstants.PADDING_TOP);
      top = val.intValue();
    }
    if (style.containsKey(StyleFormatConstants.PADDING_BOTTOM)) {
      Float val = (Float) style.get(StyleFormatConstants.PADDING_BOTTOM);
      bottom = val.intValue();
    }

    TcPr tableCellProperties = tableCell.getTcPr();
    if (tableCellProperties == null) {
      tableCellProperties = new TcPr();
      tableCell.setTcPr(tableCellProperties);
    }
    TcMar margins = new TcMar();

    if (bottom > 0) {
      TblWidth bW = new TblWidth();
      bW.setType("dxa");
      bW.setW(BigInteger.valueOf(pixelsToDxa(bottom)));
      margins.setBottom(bW);
    }

    if (top > 0) {
      TblWidth tW = new TblWidth();
      tW.setType("dxa");
      tW.setW(BigInteger.valueOf(pixelsToDxa(top)));
      margins.setTop(tW);
    }

    if (left > 0) {
      TblWidth lW = new TblWidth();
      lW.setType("dxa");
      lW.setW(BigInteger.valueOf(pixelsToDxa(left)));
      margins.setLeft(lW);
    }

    if (right > 0) {
      TblWidth rW = new TblWidth();
      rW.setType("dxa");
      rW.setW(BigInteger.valueOf(pixelsToDxa(right)));
      margins.setRight(rW);
    }

    tableCellProperties.setTcMar(margins);
  }
 private void setCellNoWrap(Tc tableCell) {
   TcPr tableCellProperties = tableCell.getTcPr();
   if (tableCellProperties == null) {
     tableCellProperties = new TcPr();
     tableCell.setTcPr(tableCellProperties);
   }
   BooleanDefaultTrue b = new BooleanDefaultTrue();
   b.setVal(true);
   tableCellProperties.setNoWrap(b);
 }
 private void setCellColor(Tc tableCell, String color) {
   if (color != null) {
     TcPr tableCellProperties = tableCell.getTcPr();
     if (tableCellProperties == null) {
       tableCellProperties = new TcPr();
       tableCell.setTcPr(tableCellProperties);
     }
     CTShd shd = new CTShd();
     shd.setFill(color);
     tableCellProperties.setShd(shd);
   }
 }
 private void setCellWidth(Tc tableCell, int width) {
   if (width > 0) {
     TcPr tableCellProperties = tableCell.getTcPr();
     if (tableCellProperties == null) {
       tableCellProperties = new TcPr();
       tableCell.setTcPr(tableCellProperties);
     }
     TblWidth tableWidth = new TblWidth();
     tableWidth.setType("dxa");
     tableWidth.setW(BigInteger.valueOf(width));
     tableCellProperties.setTcW(tableWidth);
   }
 }
  private void setVerticalAlignment(Tc tableCell, STVerticalJc align) {
    if (align != null) {
      TcPr tableCellProperties = tableCell.getTcPr();
      if (tableCellProperties == null) {
        tableCellProperties = new TcPr();
        tableCell.setTcPr(tableCellProperties);
      }

      CTVerticalJc valign = new CTVerticalJc();
      valign.setVal(align);

      tableCellProperties.setVAlign(valign);
    }
  }
 private void setCellVMerge(Tc tableCell, String mergeVal) {
   if (mergeVal != null) {
     TcPr tableCellProperties = tableCell.getTcPr();
     if (tableCellProperties == null) {
       tableCellProperties = new TcPr();
       tableCell.setTcPr(tableCellProperties);
     }
     VMerge merge = new VMerge();
     if (!"close".equals(mergeVal)) {
       merge.setVal(mergeVal);
     }
     tableCellProperties.setVMerge(merge);
   }
 }
  private void setCellHMerge(Tc tableCell, int horizontalMergedCells) {
    if (horizontalMergedCells > 1) {
      TcPr tableCellProperties = tableCell.getTcPr();
      if (tableCellProperties == null) {
        tableCellProperties = new TcPr();
        tableCell.setTcPr(tableCellProperties);
      }

      GridSpan gridSpan = new GridSpan();
      gridSpan.setVal(new BigInteger(String.valueOf(horizontalMergedCells)));

      tableCellProperties.setGridSpan(gridSpan);
      tableCell.setTcPr(tableCellProperties);
    }
  }
  private void setCellBorders(Tc tableCell, Map<String, Object> style) {

    TcPr tableCellProperties = tableCell.getTcPr();
    if (tableCellProperties == null) {
      tableCellProperties = new TcPr();
      tableCell.setTcPr(tableCellProperties);
    }

    CTBorder border = new CTBorder();
    // border.setColor("auto");
    border.setSpace(new BigInteger("0"));
    border.setVal(STBorder.SINGLE);

    TcBorders borders = new TcBorders();

    if (style.containsKey(StyleFormatConstants.BORDER_LEFT)) {
      Float val = (Float) style.get(StyleFormatConstants.BORDER_LEFT);
      border.setSz(BigInteger.valueOf((long) (val / 2)));
      Color color = (Color) style.get(StyleFormatConstants.BORDER_LEFT_COLOR);
      border.setColor(ColorUtil.getHexColor(color).substring(1));
      borders.setLeft(border);
    }
    if (style.containsKey(StyleFormatConstants.BORDER_RIGHT)) {
      Float val = (Float) style.get(StyleFormatConstants.BORDER_RIGHT);
      border.setSz(BigInteger.valueOf((long) (val / 2)));
      Color color = (Color) style.get(StyleFormatConstants.BORDER_RIGHT_COLOR);
      border.setColor(ColorUtil.getHexColor(color).substring(1));
      borders.setRight(border);
    }
    if (style.containsKey(StyleFormatConstants.BORDER_TOP)) {
      Float val = (Float) style.get(StyleFormatConstants.BORDER_TOP);
      border.setSz(BigInteger.valueOf((long) (val / 2)));
      Color color = (Color) style.get(StyleFormatConstants.BORDER_TOP_COLOR);
      border.setColor(ColorUtil.getHexColor(color).substring(1));
      borders.setTop(border);
    }
    if (style.containsKey(StyleFormatConstants.BORDER_BOTTOM)) {
      Float val = (Float) style.get(StyleFormatConstants.BORDER_BOTTOM);
      border.setSz(BigInteger.valueOf((long) (val / 2)));
      Color color = (Color) style.get(StyleFormatConstants.BORDER_BOTTOM_COLOR);
      border.setColor(ColorUtil.getHexColor(color).substring(1));
      borders.setBottom(border);
    }

    tableCellProperties.setTcBorders(borders);
  }
  private void setTextDirection(Tc tableCell, short textRotation) {
    String dir = null;
    if (textRotation == 90) {
      dir = "btLr";
    } else if (textRotation == -90) {
      dir = "tbRl";
    }

    if (dir != null) {
      TcPr tableCellProperties = tableCell.getTcPr();
      if (tableCellProperties == null) {
        tableCellProperties = new TcPr();
        tableCell.setTcPr(tableCellProperties);
      }
      TextDirection td = new TextDirection();
      td.setVal(dir);
      tableCellProperties.setTextDirection(td);
    }
  }
示例#11
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);
    }
  }