Ejemplo n.º 1
0
  private static void groupTable(Tbl table) {

    List<Object> cellElts = null;
    Tr tr = null;
    Tc tc = null;
    for (Object elemTr : table.getContent()) {
      if (elemTr instanceof JAXBElement) {
        elemTr = ((JAXBElement) elemTr).getValue();
      }
      if (elemTr instanceof Tr) {
        tr = (Tr) elemTr;
        if (tr.getContent() != null) {
          for (Object elemCe : tr.getContent()) {
            if (elemCe instanceof JAXBElement) {
              elemCe = ((JAXBElement) elemCe).getValue();
            }
            if (elemCe instanceof Tc) {
              tc = (Tc) elemCe;
              if (tc.getContent() != null) {
                cellElts = groupBodyContent(tc.getContent());
                if (cellElts != null) {
                  tc.getContent().clear();
                  tc.getContent().addAll(cellElts);
                }
              }
            }
          }
        }
      }
    }
  }
 private void addTableCell(
     Tr tableRow,
     BandElement be,
     P paragraph,
     int width,
     Map<String, Object> style,
     int horizontalMergedCells,
     String verticalMergedVal,
     boolean isImage) {
   Tc tableCell = factory.createTc();
   if (isImage) {
     addImageCellStyle(tableCell, be, paragraph, style);
   } else {
     addHyperlinkCellStyle(tableCell, be, paragraph, style);
   }
   setCellWidth(tableCell, width);
   setCellVMerge(tableCell, verticalMergedVal);
   setCellHMerge(tableCell, horizontalMergedCells);
   if (!isImage) {
     if ((be != null) && !be.isWrapText()) {
       setCellNoWrap(tableCell);
     }
   }
   tableRow.getContent().add(tableCell);
 }
Ejemplo n.º 3
0
  private void handleRow(NodeList cellContents, Tr tr, int r) {

    log.debug("Processing r " + r);

    if (borderConflictResolutionRequired
        && tr.getTblPrEx() != null
        && tr.getTblPrEx().getTblCellSpacing() != null) {
      borderConflictResolutionRequired = false;
    }

    TcFinder tcFinder = new TcFinder();
    new TraversalUtil(tr, tcFinder);

    // List<Object> cells = tr.getEGContentCellContent();
    int c = 0;
    log.debug("Processing c " + c);
    for (Tc tc : tcFinder.tcList) {

      Node wtrNode = cellContents.item(r); // w:tr
      if (wtrNode == null) {
        log.warn("Couldn't find item " + r);
      }
      addCell(tc, getTc(wtrNode, c, new IntRef(0))); // the cell content
      // addCell(tc, cellContents.item(i));
      // i++;
      c++;
    }
  }
  /**
   * In this method we create a cell and add the given content to it. If the given width is greater
   * than 0, we set the width on the cell. Finally, we add the cell to the row.
   */
  private void addStyledTableCellWithWidth(
      Tr row, String content, boolean bold, String fontSize, int width) {
    Tc tableCell = factory.createTc();
    addStyling(tableCell, content, bold, fontSize);

    if (width > 0) {
      setCellWidth(tableCell, width);
    }
    row.getContent().add(tableCell);
  }
  @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);
  }
 private void addSubreportTableCell(
     Tr tableRow,
     BandElement be,
     Tbl table,
     int width,
     Map<String, Object> style,
     int horizontalMergedCells,
     String verticalMergedVal) {
   Tc tableCell = factory.createTc();
   tableCell.getContent().add(table);
   tableCell.getContent().add(wordMLPackage.getMainDocumentPart().createParagraphOfText(""));
   setCellWidth(tableCell, width);
   setCellVMerge(tableCell, verticalMergedVal);
   setCellHMerge(tableCell, horizontalMergedCells);
   tableRow.getContent().add(tableCell);
 }
 private void addTableCell(
     Tr tableRow,
     BandElement be,
     String content,
     int width,
     Map<String, Object> style,
     int horizontalMergedCells,
     String verticalMergedVal) {
   Tc tableCell = factory.createTc();
   addCellStyle(tableCell, be, content, style);
   setCellWidth(tableCell, width);
   setCellVMerge(tableCell, verticalMergedVal);
   setCellHMerge(tableCell, horizontalMergedCells);
   if ((be != null) && !be.isWrapText()) {
     setCellNoWrap(tableCell);
   }
   tableRow.getContent().add(tableCell);
 }
Ejemplo n.º 8
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);
    }
  }
Ejemplo n.º 9
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;
  }