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

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

Introduction

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

Prototype

@Override
public List<XWPFParagraph> getParagraphs() 

Source Link

Usage

From source file:FindFile.java

public void search(String gUrl) {
    try {/*from  w w  w  .  j  ava  2s .c  o  m*/
        FileInputStream fis = new FileInputStream(gUrl);
        XWPFDocument docx = new XWPFDocument(OPCPackage.open(fis));
        List<XWPFParagraph> parag = docx.getParagraphs();
        int cntrl = 0;
        for (XWPFParagraph paraglist : parag) {
            String gelen = paraglist.getText().trim();
            String[] temp = gelen.split(" ");
            for (String temp2 : temp) {
                if (temp2.contains(srcword)) {
                    cntrl++;
                    System.out.println(cntrl + "----->" + temp2);
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:apachepoitest.ApachePOITest.java

@SuppressWarnings("empty-statement")
public static void main(String[] args) {
    try {/*  www.  j a v  a2 s.  c  o  m*/
        // Open document to check
        /*
        Writer fw = new FileWriter("C:\\Users\\Noel\\Documents\\NetBeansProjects\\ApachePOITest\\test1.json"); 
        JsonObject jo = new JsonObject().add( "name", "John" ).add( "age", 23 );
                
        JsonArray ja = new JsonArray().add( "John" ).add( 23 );
        jo.writeTo(fw);
        ja.writeTo(fw);
        fw.close();
        */
        XWPFDocument docx1 = new XWPFDocument(new FileInputStream(
                new File("C:\\Users\\Noel\\Documents\\NetBeansProjects\\ApachePOITest\\resume_only.docx")));

        // Put the following to an XML file that contains strings to check with respective properties to check
        // Question 1 in Level 1
        // Initialize strings to find
        ArrayList<String> sl = new ArrayList();
        String[] tl = { "Melissa Martin", "555 West Main St.", "Sampaloc, Metro Manila", "Phone: 312-312-3123",
                "E-mail: TeachMartin@email.com" };
        sl.addAll(Arrays.asList(tl));

        // Initialize properties these strings should have
        Map properties = new HashMap();
        properties.put("FONT FAMILY", "MV Boli");
        properties.put("FONT SIZE", "12");
        // We go through all paragraphs of the document and check for the presence of the strings
        // If they are present, check if the properties given above are present
        // Result is displayed as String = {Property1 = Score1, Property2 = Score2, ...}
        // Scores are determined by the number of elements within the paragraph which follows the given formatting
        Map<String, HashMap> results;
        results = DocumentPropertyChecker.checkRunPropertiesOfParagraphs(docx1.getParagraphs(), sl, properties);
        System.out.println("1. " + results.toString());

        //2
        tl = new String[] { "Summary", "Educational Background", "Related Work Experience",
                "Additional Work Experience" };
        sl.addAll(Arrays.asList(tl));

        //properties
        properties = new HashMap();
        properties.put("BOLD", "true");

        results = DocumentPropertyChecker.checkRunPropertiesOfParagraphs(docx1.getParagraphs(), sl, properties);
        System.out.println("2. " + results.toString());

        //3
        tl = new String[] { "Holds Bachelor's Degree in Music and Education with TEFL certification",
                "5 years experience in teaching Englsih to Spanish speaking students ages 12 and up",
                "Exceptional skills in teaching English and Spanish language",
                "Bachelor of Music; Univeristy of Sto. Tomas 2004",
                "Bachelor of Science in Education; Univerity of the Philippines 2008" };
        sl.addAll(Arrays.asList(tl));
        properties = new HashMap();
        properties.put("LINE SPACING", "1.5");

        results = DocumentPropertyChecker.checkPropertiesOfParagraphs(docx1.getParagraphs(), sl, properties);
        System.out.println("3. " + results.toString());

        //4
        tl = new String[] { "2008-2011" };
        sl.addAll(Arrays.asList(tl));
        results = DocumentPropertyChecker.checkIfStringExistsInParagraphs(docx1.getParagraphs(), sl);
        System.out.println("4. " + results.toString());

        //5
        tl = new String[] { "St. Peter's University", "2011  Present",
                "Teaches English and Spanish to students ages 15 and up",
                "Creates course materials, including exams, quizzes and visual aids used by all teachers throughout the organization",
                "Initiates programs focused in improving grammar and active listening, writing and speaking skills of students" };
        sl.addAll(Arrays.asList(tl));
        properties = new HashMap();
        properties.put("NUMBERING FORMAT", "bullet");

        results = DocumentPropertyChecker.checkPropertiesOfParagraphs(docx1.getParagraphs(), sl, properties);
        System.out.println("5. " + results.toString());

        //6
        tl = new String[] { "Black Pen Movement \u00AE" };
        sl.addAll(Arrays.asList(tl));
        results = DocumentPropertyChecker.checkIfStringExistsInParagraphs(docx1.getParagraphs(), sl);
        System.out.println("6. " + results.toString());

        //7
        properties = new HashMap();
        properties.put("MARGIN TOP", "2");
        properties.put("MARGIN BOTTOM", "2");
        properties.put("MARGIN LEFT", "2");
        properties.put("MARGIN RIGHT", "2");

        results = DocumentPropertyChecker.checkPropertiesOfDocument(docx1, properties);
        System.out.println("7. " + results.toString());

        //8
        properties = new HashMap();
        properties.put("ALIGN", "both");

        results = DocumentPropertyChecker.checkPropertiesOfAllParagraphs(docx1.getParagraphs(), properties);
        System.out.println("8. " + results.toString());

    } catch (IOException ex) {
        Logger.getLogger(ApachePOITest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:apachepoitest.DocumentPropertyEnumerator.java

public static void showProperties(XWPFDocument docx) {
    List<XWPFParagraph> lp = docx.getParagraphs();
    List<XWPFTable> lt = docx.getTables();
    showParagraphProperties(lp);/*from   w  ww .j  av  a 2  s.  c  o m*/
    showTableProperties(lt);
}

From source file:biz.webgate.dominoext.poi.component.kernel.DocumentProcessor.java

License:Apache License

public int processBookmarks2Document(XWPFDocument dxProcess, List<IDocumentBookmark> arrBookmarks) {
    // First Prozessing all paragraphs.
    for (XWPFParagraph paraCurrent : dxProcess.getParagraphs()) {
        processBookmarks2Paragraph(arrBookmarks, paraCurrent);
    }/*ww w  .ja v a  2s.c  o  m*/

    for (XWPFTable tabCurrent : dxProcess.getTables()) {
        processBookmarks2Table(arrBookmarks, tabCurrent);
    }
    for (XWPFHeader headCurrent : dxProcess.getHeaderList()) {
        for (XWPFParagraph paraCurrent : headCurrent.getParagraphs()) {
            processBookmarks2Paragraph(arrBookmarks, paraCurrent);
        }
        for (XWPFTable tabCurrent : headCurrent.getTables()) {
            processBookmarks2Table(arrBookmarks, tabCurrent);
        }
    }
    for (XWPFFooter footCurrent : dxProcess.getFooterList()) {
        for (XWPFParagraph paraCurrent : footCurrent.getParagraphs()) {
            processBookmarks2Paragraph(arrBookmarks, paraCurrent);
        }
        for (XWPFTable tabCurrent : footCurrent.getTables()) {
            processBookmarks2Table(arrBookmarks, tabCurrent);
        }
    }

    return 1;
}

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/*from   w w w .  j  a va 2 s  . c o m*/
 * @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

public void messages() {
    getKolontitules(wave_to_doc);/*from   w ww.  java2 s  .co  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 {/*  ww  w .  j a  va  2 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 XWPFDocument replaceText(XWPFDocument doc, HashMap<String, String> keys) throws Exception {
    String txt = "";
    int txtPosition = 0;
    String key = "";
    String val = "";
    for (XWPFParagraph p : doc.getParagraphs()) { //Dkmandaki her bir paragraf okumas yaplyor.
        for (XWPFRun run : p.getRuns()) { //paragraf iindeki satrlar okunuyor.
            txtPosition = run.getTextPosition();
            txt = run.getText(txtPosition);
            for (Map.Entry<String, String> entry : keys.entrySet()) { //keymap iinde gnderilen alanlar keymap'teki deerleri ile deitiriliyor.
                key = entry.getKey();//  w  w  w  .jav  a2  s  .  c  o m
                val = entry.getValue();
                if (txt != null && txt.indexOf(key) > -1) {
                    txt = txt.replace(key, val);
                    run.setText(txt, 0);
                }
            }
        }
    }

    return doc;

}

From source file:com.bxf.hradmin.testgen.service.impl.DocxTestGenerator.java

License:Open Source License

private void replaceWordHolder(XWPFDocument doc) {
    doc.getParagraphs().forEach(paragraph -> {
        Map<String, String> data = new HashMap<>();
        data.put("score", "4");
        doReplace(paragraph, data);//from   www . j ava2  s. c om
    });

    doc.getFooterList().forEach(footer -> footer.getParagraphs().forEach(paragraph -> {
        Map<String, String> data = new HashMap<>();
        data.put("year", new SimpleDateFormat("yyyy").format(new Date()));
        doReplace(paragraph, data);
    }));
}

From source file:com.ccsna.safetynet.DocReadWrite.java

public List<XWPFParagraph> readDocFile(String fileName) throws URISyntaxException, IOException {
    fileName = "/home/estelle/NetBeansProjects/CCSNA/build/web/public/aboutus.doc";
    //fileName = this.getClass().getClassLoader().getResource("").getPath() + fileName;
    //String glassfishInstanceRootPropertyName = "com.sun.aas.";
    //fileName = System.getProperty(glassfishInstanceRootPropertyName) + fileName;
    //ServletContext context = (ServletContext) getContext();
    //fileName = context.getRealPath("/WEB-INF/" + fileName);
    System.out.println("filename is : " + fileName);
    try {//from  w w w .j  a v  a  2s  .c o  m
        File file = new File(fileName);

        // to read a file from webcontent
        FileInputStream fis = new FileInputStream(file.getAbsolutePath());

        XWPFDocument document = new XWPFDocument(fis);

        List<XWPFParagraph> paragraphs = document.getParagraphs();
        //return paragraphs;

        //fis.close();
        return paragraphs;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}