コード例 #1
0
ファイル: Containerization.java プロジェクト: nanofish/docx4j
  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);
                }
              }
            }
          }
        }
      }
    }
  }
コード例 #2
0
ファイル: DOCXWriter.java プロジェクト: haxdai/SWBPDocumenter
 /**
  * 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);
 }
コード例 #3
0
  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);
  }
コード例 #4
0
 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);
 }
コード例 #5
0
 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);
   }
 }
コード例 #6
0
 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);
   }
 }
コード例 #7
0
 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);
   }
 }
コード例 #8
0
  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);
    }
  }
コード例 #9
0
  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);
    }
  }
コード例 #10
0
 /**
  * In this method we create a table cell properties object and a table width object. We set the
  * given width on the width object and then add it to the properties object. Finally we set the
  * properties on the table cell.
  */
 private void setCellWidth(Tc tableCell, int width) {
   TcPr tableCellProperties = new TcPr();
   TblWidth tableWidth = new TblWidth();
   tableWidth.setW(BigInteger.valueOf(width));
   tableCellProperties.setTcW(tableWidth);
   tableCell.setTcPr(tableCellProperties);
 }
コード例 #11
0
 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);
 }
コード例 #12
0
 private void addImageCellStyle(Tc tableCell, BandElement be, P image, Map<String, Object> style) {
   setCellMargins(tableCell, style);
   setBackground(tableCell, style);
   setVerticalAlignment(tableCell, style);
   setHorizontalAlignment(image, style);
   setCellBorders(tableCell, style);
   tableCell.getContent().add(image);
 }
コード例 #13
0
  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);
  }
コード例 #14
0
  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);
    }
  }
コード例 #15
0
  private void addCellStyle(
      Tc tableCell, BandElement be, String content, P paragraph, Map<String, Object> style) {
    if (style != null) {

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

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

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

      paragraph.getContent().add(run);

      setHorizontalAlignment(paragraph, style);

      RPr runProperties = factory.createRPr();

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

      run.setRPr(runProperties);

      tableCell.getContent().add(paragraph);
    }
  }
コード例 #16
0
  private void addHyperlinkCellStyle(
      Tc tableCell, BandElement be, P hyperlink, Map<String, Object> style) {
    setCellMargins(tableCell, style);
    setBackground(tableCell, style);
    setVerticalAlignment(tableCell, style);
    setHorizontalAlignment(hyperlink, style);
    setCellBorders(tableCell, style);

    R run = (R) ((org.docx4j.wml.P.Hyperlink) hyperlink.getContent().get(0)).getContent().get(0);
    RPr runProperties = run.getRPr();
    setFont(tableCell, style, runProperties);
    if (be != null) {
      setTextDirection(tableCell, be.getTextRotation());
    }

    tableCell.getContent().add(hyperlink);
  }
コード例 #17
0
  /**
   * This is where we add the actual styling information. In order to do this we first create a
   * paragraph. Then we create a text with the content of the cell as the value. Thirdly, we create
   * a so-called run, which is a container for one or more pieces of text having the same set of
   * properties, and add the text to it. We then add the run to the content of the paragraph. So far
   * what we've done still doesn't add any styling. To accomplish that, we'll create run properties
   * and add the styling to it. These run properties are then added to the run. Finally the
   * paragraph is added to the content of the table cell.
   */
  private void addStyling(Tc tableCell, String content, boolean bold, String fontSize) {
    P paragraph = factory.createP();

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

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

    paragraph.getContent().add(run);

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

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

    run.setRPr(runProperties);

    tableCell.getContent().add(paragraph);
  }
コード例 #18
0
  /**
   * Insert an empty placeholder SDT, to facilitate round-tripping (ie ability to convert instance
   * docx back to original template), which you may wish to do if you want to insert updated data,
   * but preserve certain manual edits.
   *
   * @param sdt
   * @return
   */
  private List<Object> repeatZero(Object sdt) {

    List<Object> newContent = new ArrayList<Object>();

    //		if (removeSdtCellsOnFailedCondition) {
    //			// backward compatibility
    //			// NB this is not compatible with reverting functionality, and
    //			// will break if the result is an empty tc
    //			return newContent;
    //		}

    newContent.add(sdt);

    // Change the tag to od:resultRepeatZero
    SdtPr sdtPr = getSdtPr(sdt);

    CTDataBinding binding = sdtPr.getDataBinding();
    if (binding != null) { // Shouldn't be a binding anyway
      sdtPr.getRPrOrAliasOrLock().remove(binding);
    }

    Tag tag = sdtPr.getTag();

    final String tagVal = tag.getVal();
    final Pattern stripRepeatArgPattern = Pattern.compile("(.*od:repeat=)([^&]*)(.*)");
    final Matcher stripPatternMatcher = stripRepeatArgPattern.matcher(tagVal);
    if (!stripPatternMatcher.matches()) {
      log.error(
          "Cannot find repeat tag in sdtPr/tag while processing repeat; something is wrong with "
              + tagVal);
      return newContent;
    }
    final String emptyRepeatValue =
        BINDING_RESULT_RPTD_ZERO
            + "="
            + stripPatternMatcher.group(2)
            + stripPatternMatcher.group(3);
    tag.setVal(emptyRepeatValue);

    // Lock it
    CTLock lock = Context.getWmlObjectFactory().createCTLock();
    lock.setVal(org.docx4j.wml.STLock.SDT_CONTENT_LOCKED);
    JAXBElement<org.docx4j.wml.CTLock> lockWrapped =
        Context.getWmlObjectFactory().createSdtPrLock(lock);
    sdtPr.getRPrOrAliasOrLock().add(lockWrapped); // assumes no lock is there already

    // Empty the content
    // .. OpenDoPEIntegrity fixes this where it is not OK, but
    // where it needs to insert a tc, it has no way of adding original tcPr, so
    // we handle this here
    TcFinder tcFinder = new TcFinder();
    new TraversalUtil(((SdtElement) sdt).getSdtContent().getContent(), tcFinder);
    if (tcFinder.tcList.size() > 0) {
      Tc tc = tcFinder.tcList.get(0);
      tc.getContent().clear();
      P p = Context.getWmlObjectFactory().createP();
      tc.getContent().add(p);
      ((SdtElement) sdt).getSdtContent().getContent().clear();
      ((SdtElement) sdt).getSdtContent().getContent().add(tc);
    } else {
      ((SdtElement) sdt).getSdtContent().getContent().clear();
    }

    return newContent;
  }
コード例 #19
0
ファイル: DOCXWriter.java プロジェクト: haxdai/SWBPDocumenter
  @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);
    }
  }
コード例 #20
0
ファイル: TableModel.java プロジェクト: sike1406/docx4j
  /* (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;
  }