Exemple #1
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()));
       }
   }
 }
  public static void main(String[] args) throws Exception {

    System.out.println("Creating package..");
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title", "Hello world");

    wordMLPackage.getMainDocumentPart().addParagraphOfText("from docx4j!");

    CustomXmlDataStoragePart customXmlDataStoragePart =
        injectCustomXmlDataStoragePart(wordMLPackage.getMainDocumentPart());

    addProperties(customXmlDataStoragePart);

    // Now save it
    wordMLPackage.save(
        new java.io.File(
            System.getProperty("user.dir") + "/OUT_withCustomXmlDataStoragePart.docx"));
  }
 @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);
   }
 }
  @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);
    }
  }
  /**
   * 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();
    }
  }
  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"));
  }