Example usage for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument

List of usage examples for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument

Introduction

In this page you can find the example usage for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument.

Prototype

public XWPFDocument(InputStream is) throws IOException 

Source Link

Usage

From source file:certificatecreator.CertificateCreator.java

private void createStudentCertificate(String tempPath) {
    //Creates student certificate.
    //Read in template file and define output file.
    File inFile = new File(tempPath);
    File outFile = new File(userPath + File.separator + selectedStudent + "Certificate.docx");
    //Create output file. Throw alert if tempPath references nonexisting file.
    try {/*from w w  w  .j av a 2 s  .  c  om*/
        copy(inFile, outFile);
        //Create internal word document based on copied template file. Write content.
        try {
            XWPFDocument certificate = new XWPFDocument(new FileInputStream(outFile));
            XWPFParagraph p1 = certificate.createParagraph();
            p1.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun r1 = p1.createRun();
            r1.setFontFamily("Candara");
            r1.setFontSize(40);
            r1.addBreak();
            r1.setText("Lawton Elementary Congratulates");
            XWPFRun r2 = p1.createRun();
            r2.setFontFamily("Candara");
            r2.setFontSize(36);
            r2.setBold(true);
            r2.addBreak();
            r2.addBreak();
            r2.setText(selectedStudent);
            r2.addBreak();
            r2.addBreak();
            XWPFRun r3 = p1.createRun();
            r3.setFontFamily("Candara");
            r3.setFontSize(26);
            r3.setText("For being a Lawton CARES winner on");
            r3.addBreak();
            String date = getDate();
            r3.setText(date);
            r3.addBreak();
            r3.addBreak();
            r3.addBreak();
            r3.addBreak();
            XWPFRun r4 = p1.createRun();
            r4.setColor("5B9BD5");
            r4.setFontFamily("Candara");
            r4.setFontSize(26);
            r4.setText("Compassion+Attitude+Respect+Effort+Safety=CARES");
            //Write internal document to copied templated file.
            try {
                FileOutputStream out = new FileOutputStream(outFile.toString());
                try {
                    certificate.write(out);
                    out.close();
                } catch (IOException io) {
                    System.err.println("Could not write file: " + io);
                }
            } catch (FileNotFoundException fnf) {
                System.err.println("Could not find output file: " + fnf);
            }
        } catch (IOException io) {
            System.err.println("Copy of template could not be found: " + io);
        }
    } catch (IOException io) {
        System.err.println("Method copy failed:" + io);
    } catch (NullPointerException npe) {
        System.err.println("Method copy failed:" + npe);
        Alert templateNotFound = new Alert(AlertType.WARNING,
                "Specified certificate template was not found. " + "Please choose a different template.");
        templateNotFound.showAndWait();
    }
}

From source file:ch.admin.isb.hermes5.business.word.Docx4jWordDocumentCustomizerTest.java

License:Apache License

private Map<String, String> getTableMap(byte[] result) throws IOException {
    Map<String, String> map = new HashMap<String, String>();
    XWPFDocument document = new XWPFDocument(new ByteArrayInputStream(result));
    List<XWPFTable> tables = new ArrayList<XWPFTable>();
    tables.addAll(document.getTables());
    List<XWPFHeader> headers = document.getHeaderList();
    for (XWPFHeader header : headers) {
        tables.addAll(header.getTables());
    }//ww w . j  ava 2 s  .  co  m
    for (XWPFTable xwpfTable : tables) {
        List<XWPFTableRow> rows = xwpfTable.getRows();
        for (XWPFTableRow xwpfTableRow : rows) {
            List<XWPFTableCell> tableCells = xwpfTableRow.getTableCells();
            if (tableCells.size() == 2) {
                map.put(tableCells.get(0).getText(), tableCells.get(1).getText());
            }
            if (tableCells.size() == 1) {
                map.put(tableCells.get(0).getText(), "");
            }
        }
    }

    return map;
}

From source file:ch.admin.isb.hermes5.business.word.TranslationWordAdapter.java

License:Apache License

public List<TranslateableText> read(InputStream in, String docLang) {
    List<TranslateableText> result = new ArrayList<TranslateableText>();
    XWPFDocument document = null;//from ww w  . ja  v a 2s . com
    try {
        document = new XWPFDocument(in);
        in.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
    List<XWPFTableRow> rows = document.getTables().get(0).getRows();
    for (XWPFTableRow r : rows) {
        String[] identifiers = r.getCell(0).getText().split("\\/");
        if (identifiers.length != 2) {
            throw new RuntimeException("Unable to parse identifier " + r.getCell(0).getText());
        }
        TranslateableText text = new TranslateableText("", "", "", "", "", identifiers[0].trim(),
                identifiers[1].trim(), "");
        if (docLang.equals("fr")) {
            text.setTextFr(r.getCell(1).getText());
        }
        if (docLang.equals("it")) {
            text.setTextIt(r.getCell(1).getText());
        }
        if (docLang.equals("en")) {
            text.setTextEn(r.getCell(1).getText());
        }
        result.add(text);
    }
    return result;
}

From source file:ch.admin.isb.hermes5.tools.translator.Translator.java

License:Apache License

public byte[] translateWordFile(InputStream in, String lang) {
    XWPFDocument document = null;//from ww w  .  j a  va2 s  .  c  om
    try {
        document = new XWPFDocument(in);
        in.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
    List<XWPFTableRow> rows = document.getTables().get(0).getRows();
    for (XWPFTableRow r : rows) {
        r.getCell(1).setText(lang + " " + lang);
    }
    try {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        document.write(outStream);
        return outStream.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:ch.admin.searchreplace.SearchReplace.java

License:Apache License

/**
 * The constructor which opens the named Word file.
 * //from   ww  w.  j a  v  a 2 s.  c  om
 * @param filename An instance of the String class that encapsulates the name of and path to a Word (.docx)
 *            document.
 * @throws java.io.IOException Thrown if a problem is encountered opening and InutStream onto the Word file.
 */
public SearchReplace(String filename) throws IOException {
    InputStream is = null;
    try {
        this.sourceFile = new File(filename);
        // Verify the the Word document exists and can be read
        if (this.sourceFile.exists() || this.sourceFile.canRead()) {

            // Attach a FileInputStream to the Word document file
            // and read it's contents into memory.
            is = new FileInputStream(this.sourceFile);
            this.doc = new XWPFDocument(is);
            this.srTerms = new Hashtable<String, String>();
        } else {
            throw new IllegalArgumentException("The file " + filename + " is not accessible.");
        }
    } catch (IOException ioEx) {
        System.out.println("IOException thrown opening Word document.");
        throw new IOException(ioEx);
    } finally {
        try {
            is.close();
        } catch (IOException ioEx) {
            System.out.println("IOException thrown closing InputStream.");
            throw new IOException(ioEx);
        }
    }
}

From source file:ch.admin.searchreplace.SearchReplaceTerms.java

License:Apache License

/**
 * Ersetzt eine Liste von Ausdruecken in einer Datei und schreibt das Resultat nach Output
 * @param input Inputdatei/*  w w w  . j a va 2s .c  om*/
 * @param output Outputdatei
 * @param srTerms Begriff
 * @throws IOException I/O Fehler
 * @throws InvalidFormatException OpenXML Document korrupt
 * @throws FileNotFoundException Datei nicht vorhanden
 */
private static void searchReplaceInFile(String input, String output, HashMap<String, String> srTerms)
        throws IOException, InvalidFormatException, FileNotFoundException {
    XWPFDocument doc = new XWPFDocument(OPCPackage.open(input));

    // Header
    List<XWPFHeader> header = doc.getHeaderList();
    for (Iterator<XWPFHeader> e = header.iterator(); e.hasNext();) {
        XWPFHeader h = e.next();
        for (XWPFParagraph p : h.getParagraphs()) {
            XWPFRun r = consolidateRuns(p);
            if (r != null)
                searchReplace(srTerms, r);
        }
        for (XWPFTable tbl : h.getTables())
            for (XWPFTableRow row : tbl.getRows())
                for (XWPFTableCell cell : row.getTableCells())
                    for (XWPFParagraph p : cell.getParagraphs()) {
                        XWPFRun r = consolidateRuns(p);
                        if (r != null)
                            searchReplace(srTerms, r);
                    }
    }

    // Document
    for (XWPFParagraph p : doc.getParagraphs()) {
        XWPFRun r = consolidateRuns(p);
        if (r != null)
            searchReplace(srTerms, r);
    }
    for (XWPFTable tbl : doc.getTables())
        for (XWPFTableRow row : tbl.getRows())
            for (XWPFTableCell cell : row.getTableCells())
                for (XWPFParagraph p : cell.getParagraphs()) {
                    XWPFRun r = consolidateRuns(p);
                    if (r != null)
                        searchReplace(srTerms, r);
                }

    doc.write(new FileOutputStream(output));
}

From source file:checking_doc.info.java

private static void getKolontitules(String wave) {
    try {//from  w w w. j av  a  2 s.  c  o m
        FileInputStream fileInputStream = new FileInputStream(wave);
        //    ?  ?   XWPFDocument
        XWPFDocument docxFile = new XWPFDocument(OPCPackage.open(fileInputStream));
        XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(docxFile);

        // ?   ( )
        XWPFHeader docHeader = headerFooterPolicy.getDefaultHeader();
        HighKolontit = docHeader.getText();
        XWPFFooter docFooter = headerFooterPolicy.getDefaultFooter();
        LowKolontit = docFooter.getText();
        fileInputStream.close();
    } catch (Exception e) {

    }
}

From source file:checking_doc.info.java

public void messages() {
    getKolontitules(wave_to_doc);//from w w w. j a va 2  s  .c o m
    boolean error = true;
    if (HighKolontit == null) {
        JOptionPane.showMessageDialog(null,
                "<html><h2>!!!</h2><i>  ? </i>");
        error = false;
    }
    if (LowKolontit == null) {
        JOptionPane.showMessageDialog(null,
                "<html><h2>!!!</h2><i>?  ? </i>");
        error = false;
    }
    try {
        FileInputStream fileInputStream = new FileInputStream(wave_to_doc);
        XWPFDocument docxFile = new XWPFDocument(OPCPackage.open(fileInputStream));
        List<XWPFParagraph> paragraphs = docxFile.getParagraphs();
        String UDK;
        UDK = paragraphs.get(0).getText();
        if (UDK.indexOf("") == -1) {
            JOptionPane.showMessageDialog(null,
                    "<html><h2>!!!</h2><i>?? ?  </i>");
            error = false;
        }

        if (UDK.equals("") || UDK.equals(" ")) {
            JOptionPane.showMessageDialog(null,
                    "<html><h2>!!!</h2><i>??   </i>");
            error = false;
        }

        if (error) {
            JOptionPane.showMessageDialog(null,
                    "<html><h2>!!!</h2><i>,  ? , <br> ?- </i>");
        }
        if (!error) {
            JOptionPane.showMessageDialog(null,
                    "<html><h2>?   ...</h2><i>  worda ?  </i>");
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:colina.angel.controller.CreadorController.java

private void procesar() {

    try {// w w  w .j ava2 s  . c  o  m
        fechaActual = new Date();
        InputStream st = ClassLoader.getSystemResource("Carta de Renuncia.docx").openStream();

        XWPFDocument document = new XWPFDocument(st);
        Field fields[] = ReflectionUtils.getAllFields(this.getClass());
        document.getParagraphs().parallelStream().forEach(p -> {
            StringBuilder sb = new StringBuilder(p.getText());
            Arrays.stream(fields).forEach(f -> {
                StringBuilder name = new StringBuilder();
                name.append("{").append(f.getName()).append("}");
                int start = sb.indexOf(name.toString());
                if (start != -1) {
                    String value = "";
                    if (f.getAnnotation(CustomValue.class) != null) {
                        value = getCustomValue(f.getName());
                    } else if (JDateChooser.class.isAssignableFrom(f.getType())) {
                        value = formatearFecha(
                                ((JDateChooser) ReflectionUtils.getFieldValue(f, this)).getDate());
                    } else if (JTextField.class.isAssignableFrom(f.getType())) {
                        value = ((JTextField) ReflectionUtils.getFieldValue(f, this)).getText();
                    } else if (JTextArea.class.isAssignableFrom(f.getType())) {
                        value = ((JTextArea) ReflectionUtils.getFieldValue(f, this)).getText();
                    }
                    sb.replace(start, start + name.length(), value);
                    changeText(p, sb.toString());

                }
            });
        });

        int opc = fileChooser.showSaveDialog(this);

        if (opc == 0) {
            File f = fileChooser.getSelectedFile();
            if (!f.getName().endsWith(".docx")) {
                f = new File(f.toString().concat(".docx"));
            }

            FileOutputStream fo = new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(fo);
            document.write(bos);
            JOptionPane.showMessageDialog(this,
                    "La carta ha sido guardada en la siguiente ruta \"".concat(f.toString()).concat("\""),
                    "Carta guardada con exito", JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(this, ex.getMessage(), "Error al guardar", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.altar.worddocreader.WordDocReaderMain.java

public static void readWordDoc(String orginalFilePath, String newFilePath, HashMap<String, String> keyMap) {
    FileInputStream fis = null;//from   ww w  .  ja  v  a2s .c  o m
    FileOutputStream out = null;
    try {
        fis = new FileInputStream(orginalFilePath);
        XWPFDocument doc = new XWPFDocument(fis);
        doc = replaceText(doc, keyMap);

        out = new FileOutputStream(new File(newFilePath)); // yeni dosya oluturuluyor. 
        doc.write(out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                if (out != null) {
                    out.close();
                }
                fis.close();
                out = null;
                fis = null;
            } catch (IOException ioEx) {
                ioEx.printStackTrace();
            }
        }
    }
}