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:fr.univrouen.poste.services.WordParser.java

License:Apache License

public void modifyWord(InputStream docx, Map<String, String> textMap, OutputStream out) {
    try {//from  w w  w. j  a v  a2 s .com
        XWPFDocument doc = new XWPFDocument(OPCPackage.open(docx));

        // tentative avec les noms {{}}
        for (XWPFParagraph p : doc.getParagraphs()) {

            for (CTBookmark bookmark : p.getCTP().getBookmarkStartList()) {
                log.trace(bookmark.getName());
                for (String key : textMap.keySet()) {
                    String cleanKey = StringUtils.stripAccents(key);
                    cleanKey = cleanKey.replaceAll(" ", "_");
                    cleanKey = cleanKey.replaceAll("\\W", "");
                    if (bookmark.getName().equalsIgnoreCase(cleanKey)) {
                        Node nextNode = bookmark.getDomNode().getNextSibling();
                        while (nextNode != null && nextNode.getNodeName() != null
                                && !(nextNode.getNodeName().contains("bookmarkEnd"))) {
                            p.getCTP().getDomNode().removeChild(nextNode);
                            nextNode = bookmark.getDomNode().getNextSibling();
                        }
                        XWPFRun run = p.createRun();
                        run.setText(textMap.get(key));
                        p.getCTP().getDomNode().insertBefore(run.getCTR().getDomNode(), nextNode);
                    }
                }
            }
        }

        doc.write(out);
    } catch (Exception e) {
        log.error("Pb durant la modification du document word", e);
    }

}

From source file:gob.osinergmin.inpsweb.service.business.impl.PlantillaResultadoServiceNegImpl.java

private XWPFDocument armarPlantilla(PlantillaResultadoDTO plantilla, Long idSupervision)
        throws PlantillaResultadoException {
    LOG.info("armarPlantilla");
    XWPFDocument document = null;// w  w w  .  ja  v  a  2  s .c  om
    try {
        String direccion = RUTA_PLANTILLAS + plantilla.getCarpeta() + plantilla.getNombreDocumento();
        FileInputStream fis = new FileInputStream(direccion);
        document = new XWPFDocument(OPCPackage.open(fis));
        fis.close();

        Map<String, Map<String, Object>> datos = null;
        if (plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_UNO)) {
            datos = datoPlantillaServiceNeg.obtenerDatosPlantillaUno(idSupervision);
        } else if (plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_DOS)) {
            datos = datoPlantillaServiceNeg.obtenerDatosPlantillaDos(idSupervision);
        } else if (plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_TRES)) {
            datos = datoPlantillaServiceNeg.obtenerDatosPlantillaTres(idSupervision);
        } else if (plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_CUATRO)) {
            datos = datoPlantillaServiceNeg.obtenerDatosPlantillaCuatro(idSupervision);
        } else if (plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_CINCO)) {
            datos = datoPlantillaServiceNeg.obtenerDatosPlantillaCinco(idSupervision);
        } else if (plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_SEIS)) {
            datos = datoPlantillaServiceNeg.obtenerDatosPlantillaSeis(idSupervision);
        } else if (plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_SIETE)) {
            datos = datoPlantillaServiceNeg.obtenerDatosPlantillaSiete(idSupervision);
        } else if (plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_OCHO) || //mdiosesf - RSIS5 
                plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_NUEVE)
                || plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_DIEZ)
                || plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_ONCE)
                || plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_DOCE)
                || plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_TRECE)
                || plantilla.getIdentificadorPlantilla().equals(Constantes.IDENT_PLANTILLA_CATORCE)) {
            datos = datoPlantillaServiceNeg.obtenerDatosPlantillaNoSupervisada(idSupervision);
        } else {
            throw new PlantillaResultadoException("Plantilla no existe", null);
        }

        document = Utiles.Poi.actualizaPlantilla(document, datos);
    } catch (Exception ex) {
        LOG.error("armaPlantilla", ex);
        throw new PlantillaResultadoException(ex.getMessage(), ex);
    }
    return document;
}

From source file:indexer.Indexer.java

/**
 * @param filePath/*from   w  ww .j ava  2s . co  m*/
 * @return
 */
// KIND OF USELESS
public static String getText(String filePath) {
    File file;
    String fd = null;
    XWPFWordExtractor extractor;
    try {
        file = new File(filePath);
        FileInputStream fis = new FileInputStream(file.getAbsolutePath());
        XWPFDocument document = new XWPFDocument(fis);
        extractor = new XWPFWordExtractor(document);
        fd = extractor.getText();
    } catch (IOException exep) {
        exep.printStackTrace();
    }
    return fd;
}

From source file:IsiXhosa_spellchecker.Spellchecker.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // Open file from machine
    int returnVal = fileChooser.showOpenDialog(this);
    boolean English = jRadioButton1.isSelected();
    if (English)//from w  w w  .  j  ava 2 s  .c om
        instruction.setText("Spellcheck to check for errors");
    else
        instruction.setText("Cofa uSebenzisa ukuze uhlole amaphutha");
    instruction.setForeground(Color.BLUE);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        String name = file.getName();
        String ext = name.substring(name.indexOf("."), name.length());

        try {
            // What to do with the file, e.g. display it in a TextArea
            if (highlightSet) {
                highlighter.removeAllHighlights();
            }
            if (name.endsWith(".docx")) {
                FileInputStream fis = new FileInputStream(file.getAbsolutePath());
                XWPFDocument docx = new XWPFDocument(fis);
                List<XWPFParagraph> pars = docx.getParagraphs();
                String toDisplay = "";
                for (XWPFParagraph para : pars) {
                    toDisplay += para.getText() + "\n";
                }

                textArea.setText(toDisplay);
                text = textArea.getText();
            } else {
                textArea.read(new FileReader(file.getAbsolutePath()), null);
                text = textArea.getText(); //for controlling the displayed text
            }
        } catch (IOException ex) {
            System.out.println("problem accessing file" + file.getAbsolutePath());
        }
    }
    //Resets globals used by other buttons such as ignoreAll
    pos = 0;
    sentNo = 0;
    wordNo = 0;

}

From source file:isizulu_spellchecker.Spellchecker.java

private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed
    // TODO add your handling code here:          
    int returnVal = fileChooser.showOpenDialog(this);
    if (language)
        instruction.setText("Click run to check for errors");
    else/*from w  ww . j  a v  a2 s .  co m*/
        instruction.setText("Cofa uSebenzisa ukuze uhlole amaphutha");
    instruction.setForeground(Color.BLUE);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        String name = file.getName();
        String ext = name.substring(name.indexOf("."), name.length());

        try {
            // What to do with the file, e.g. display it in a TextArea
            if (highlightSet) {
                highlighter.removeAllHighlights();
            }
            if (name.endsWith(".docx")) {
                FileInputStream fis = new FileInputStream(file.getAbsolutePath());
                XWPFDocument docx = new XWPFDocument(fis);
                List<XWPFParagraph> pars = docx.getParagraphs();
                String toDisplay = "";
                for (XWPFParagraph para : pars) {
                    toDisplay += para.getText() + "\n";
                }

                textArea.setText(toDisplay);
                text = textArea.getText();
            } else {
                textArea.read(new FileReader(file.getAbsolutePath()), null);
                text = textArea.getText(); //for controlling the displayed text
            }
        } catch (IOException ex) {
            System.out.println("problem accessing file" + file.getAbsolutePath());
        }
    }
    //Resets globals used by other buttons such as ignoreAll
    pos = 0;
    sentNo = 0;
    wordNo = 0;
}

From source file:javaapplication1.AnotherPOI.java

public static void replaceText(String findText, String replaceText) {
    try {/*  w w  w . j ava 2s.co  m*/
        XWPFDocument doc = new XWPFDocument(OPCPackage.open("D:\\template.docx"));
        for (XWPFParagraph p : doc.getParagraphs()) {

            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                for (XWPFRun r : runs) {
                    String text = r.getText(0);
                    if (text != null && text.contains(findText)) {
                        text = text.replace(findText, replaceText);
                        r.setText(text, 0);
                    }
                }
            }
        }
        for (XWPFTable tbl : doc.getTables()) {
            for (XWPFTableRow row : tbl.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph p : cell.getParagraphs()) {
                        for (XWPFRun r : p.getRuns()) {
                            String text = r.getText(0);
                            if (text.contains(findText)) {
                                text = text.replace(findText, replaceText);
                                r.setText(text);
                            }
                        }
                    }
                }
            }
        }
        doc.write(new FileOutputStream("D:\\result.docx"));
    } catch (IOException ex) {
        Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidFormatException ex) {
        Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:kz.service.DocumentReader.java

public static String readDocxFile(String fileName) {

    try {//from  w  w  w.  j a  v  a2 s .c  o m
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file.getAbsolutePath());
        StringBuffer content = new StringBuffer();

        XWPFDocument document = new XWPFDocument(fis);
        XWPFStyles styles = document.getStyles();

        List<XWPFParagraph> paragraphs = document.getParagraphs();
        List<XWPFTable> tables = document.getTables();
        List<XWPFPictureData> pictures = document.getAllPictures();

        //int Picture_ID = 0;
        for (XWPFPictureData picture : pictures) {
            //XWPFPictureData picture = pictures.get(Picture_ID);
            System.out.println("Picture: " + picture.getFileName());
            byte[] pictureData = picture.getData();
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(pictureData));
            ImageIO.write(image, picture.getFileName(), file);
            content.append("<p>");
            content.append("Here must be image");
            content.append("</p>");
            //Picture_ID++;
        }

        Iterator<IBodyElement> bodyElementIterator = document.getBodyElementsIterator();
        int Table_ID = 0;
        int Paragraph_ID = 0;
        while (bodyElementIterator.hasNext()) {

            IBodyElement element = bodyElementIterator.next();
            System.out.println(element.getElementType().name());//prints Element type name

            if ("TABLE".equalsIgnoreCase(element.getElementType().name())) {

                content.append("<table>");
                XWPFTable table = tables.get(Table_ID);
                CTTbl cttbl = table.getCTTbl();
                CTTblPr cttblPr = cttbl.getTblPr();

                List<XWPFTableRow> tblRows = table.getRows();
                for (XWPFTableRow tblRow : tblRows) {
                    content.append("<tr>");
                    List<XWPFTableCell> tblCells = tblRow.getTableCells();
                    for (XWPFTableCell tblCell : tblCells) {
                        content.append("<td>");
                        content.append(tblCell.getText());
                        content.append("</td>");
                    }
                    content.append("</tr>");
                }
                content.append("</table>");
                Table_ID++;

            } else if ("PARAGRAPH".equalsIgnoreCase(element.getElementType().name())) {

                XWPFParagraph paragraph = paragraphs.get(Paragraph_ID);

                String styleClass = null;
                if (paragraph.getStyleID() != null) {
                    content.append("<p class=''>");
                    XWPFStyle style = styles.getStyle(paragraph.getStyleID());
                    if (style != null && style.getName() != null) {
                        //here will be code creation of tag with class style
                    }
                } else {
                    content.append("<p>");
                }
                content.append(paragraph.getText());
                content.append("</p>");
                Paragraph_ID++;

            }
        }

        fis.close();
        return content.toString();
    } catch (Exception e) {
        return e.toString();
    }

}

From source file:LAB.ReportCreate.java

private void ReadDocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReadDocActionPerformed
    try {/*from w  w w .j  ava2 s. co  m*/
        JFileChooser s = new JFileChooser();
        s.showOpenDialog(null);
        XWPFDocument d = new XWPFDocument(new FileInputStream(s.getSelectedFile()));
        XWPFWordExtractor extract = new XWPFWordExtractor(d);
        contest.setText(extract.getText());

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Do you want to leave");
    }

}

From source file:lisa.ExtractText.java

License:Open Source License

private static String parseDOCX(String file) {
    try {/*from  w  w  w  .  ja  v  a 2  s . co  m*/
        BufferedInputStream isr = new BufferedInputStream(new FileInputStream(file));
        XWPFWordExtractor word = new XWPFWordExtractor(new XWPFDocument(isr));
        return word.getText();
    } catch (Exception e) {
        Common.createLog(e);
        return "";
    }
}

From source file:mc.program.Importer.java

public void importDOCX() {
    try {//from   www  .  ja v  a 2 s.c  om
        // Set up objects for getting from .docx file
        FileInputStream fis = new FileInputStream(sourceFile.getAbsolutePath());
        XWPFDocument document = new XWPFDocument(fis);
        XWPFWordExtractor extractor = new XWPFWordExtractor(document);

        // Extract text
        String fileData = extractor.getText();

        // Put text into array list
        Scanner scanner = new Scanner(fileData);
        while (scanner.hasNext()) {
            sourceText.add(scanner.next());
        }

        fis.close();
        extractor.close();
    } catch (Exception ex) {
        System.out.print(ex);
    }
}