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:FindFile.java

public void search(String gUrl) {
    try {/*from  w  w w. ja va2s. co  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 .ja  v  a  2s . co 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:authorslilhelper.FXMLDocumentController.java

License:Open Source License

public void loadWordDocument() {
    try {/*from   ww w. j  a v a 2 s .  c  om*/
        JFileChooser chooser = new JFileChooser();
        int value = chooser.showOpenDialog(null);
        if (value == JFileChooser.APPROVE_OPTION) {
            XWPFDocument docToAppend = new XWPFDocument(new FileInputStream(chooser.getSelectedFile()));
            XWPFWordExtractor extract = new XWPFWordExtractor(docToAppend);
            String fullText = extract.getText();

            /*                            for(int q = 0; q < fullText.length(); q++)
                    {
                        if(q < fullText.length() - 3)
                        {
                            if(fullText.charAt(q) == '\n' && fullText.charAt(q+1) == '\t')
                            {
                                fullText = fullText.substring(0, q) + "\n\n" + fullText.substring(q + 1, fullText.length() - 1);
                            }
                        }
                    }*/ //newly bracketed out

            //Primary.appendText(extract.getText());

            String[] buttons = { "Append to end", "Insert at cursor location" };
            int result = JOptionPane.showOptionDialog(null, "How would you like to insert the text? ",
                    "Insert Text", JOptionPane.WARNING_MESSAGE, 0, null, buttons, buttons[1]);

            if (result == 0) {
                try {
                    //FileReader reader = new FileReader(fileLocation);
                    //InputStream in = IOUtils.toInputStream(fullText, "UTF-8");
                    StringReader reader = new StringReader(fullText);
                    BufferedReader br = new BufferedReader(reader);

                    String s;
                    int index = 0;
                    //int charCounter = 0;

                    boolean endOfPara = false;

                    while ((s = br.readLine()) != null) {
                        index = 0;
                        while (index < s.length()) //change this
                        {

                            if ((index == characterCapacity) && (index < s.length() - 1)) {
                                while (s.charAt(index) != ' ') {
                                    index--;
                                }

                                String n = s.substring(0, index);
                                s = s.substring(index);

                                Primary.appendText(n + "\n");

                                index = 0;
                            } else if ((index == s.length() - 1) && (index <= characterCapacity)
                                    && (s.length() > 0)) {
                                Primary.appendText(s + "\n");
                                index = s.length(); //OR use break;
                                endOfPara = true;
                            } else {
                                index++;
                            }

                        }

                        if (endOfPara == true) {
                            Primary.appendText("\n");
                        }

                        endOfPara = false;
                    }

                } catch (Exception e) {

                }
                //Primary.appendText(fullText);

                //resetOnPaste();
                onClickOrKeyPress();

                /*save();
                Primary.selectAll();
                Primary.clear();
                reinitializePrimary();*/

                String pathToSave = chooser.getSelectedFile().getAbsolutePath();

                //adds the loaded file's name/path to the filetracker
                File filesLoadedLog = new File(installationPath + "/FileTracker" + currentUser);
                FileWriter writ = new FileWriter(filesLoadedLog, true);
                BufferedWriter bw = new BufferedWriter(writ);
                //writ.append("Hello World");
                // if(filesLoadedLog.exists() == true)
                // {
                writ.append(pathToSave + "\n");
                //     title.setText(fileLocation);
                // }
                // else
                // {
                //     writ.write(fileLocation);
                //     title.setText(fileLocation);
                // }

                bw.close();
                writ.close();

            }
            if (result == 1) {

                Primary.insertText(Primary.getCaretPosition(), "\n");
                //Primary.nextWord();
                //Primary.forward();

                int desiredCaretPosition = Primary.getCaretPosition();
                Primary.end();
                int start = Primary.getCaretPosition();

                try {
                    StringReader reader = new StringReader(fullText);
                    BufferedReader br = new BufferedReader(reader);
                    //FileReader reader = new FileReader(fileLocation);
                    //BufferedReader br = new BufferedReader(reader); 
                    String s;
                    int index = 0;
                    //int charCounter = 0;

                    boolean endOfPara = false;

                    while ((s = br.readLine()) != null) {
                        index = 0;
                        while (index < s.length()) //change this
                        {

                            if ((index == characterCapacity) && (index < s.length() - 1)) {
                                while (s.charAt(index) != ' ') {
                                    index--;
                                }

                                String n = s.substring(0, index);
                                s = s.substring(index);

                                Primary.appendText(n + "\n");

                                index = 0;
                            } else if ((index == s.length() - 1) && (index <= characterCapacity)
                                    && (s.length() > 0)) {
                                Primary.appendText(s + "\n");
                                index = s.length(); //OR use break;
                                endOfPara = true;
                            } else {
                                index++;
                            }

                        }

                        if (endOfPara == true) {
                            Primary.appendText("\n");
                        }

                        endOfPara = false;
                    }

                } catch (Exception e) {

                }

                Primary.end();
                int end = Primary.getCaretPosition();
                Primary.selectRange(start, end);
                String appendedText = Primary.getSelectedText();
                Primary.deleteText(start, end);

                Primary.insertText(desiredCaretPosition, appendedText);

                //                       int caretPosition = Primary.getCaretPosition();        //NEWLY BRACKETED OUT
                //                       Primary.insertText(caretPosition, fullText);           //NEWLY BRACKETED OUT

                //resetOnPaste();
                onClickOrKeyPress();

                /*save();
                Primary.selectAll();
                Primary.clear();
                reinitializePrimary();*/

                String pathToSave = chooser.getSelectedFile().getAbsolutePath();

                //adds the loaded file's name/path to the filetracker
                File filesLoadedLog = new File(installationPath + "/FileTracker" + currentUser);
                FileWriter writ = new FileWriter(filesLoadedLog, true);
                BufferedWriter bw = new BufferedWriter(writ);
                //writ.append("Hello World");
                // if(filesLoadedLog.exists() == true)
                // {
                writ.append(pathToSave + "\n");
                //     title.setText(fileLocation);
                // }
                // else
                // {
                //     writ.write(fileLocation);
                //     title.setText(fileLocation);
                // }

                bw.close();
                writ.close();

            }

        } else {

        }

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null,
                "Images are not supported. If your document contains images, it will not be loaded. Please remove the images or paste the text into another document and try again.");
    }
}

From source file:avoking.com.documentos.scheduler.core.Core.java

private String leerDocx(InputStream docx) throws IOException {
    //Se crea un documento que la POI entiende pasandole el stream
    //instanciamos el obj para extraer contenido pasando el documento
    XWPFWordExtractor xwpf_we = new XWPFWordExtractor(new XWPFDocument(docx));

    return xwpf_we.getText();
}

From source file:avoking.com.documentos.scheduler.startup.Main.java

public static void main(String[] args) {
    //        SplashWindow s = new SplashWindow("E:\\Documentos\\NetBeansProjects\\documentos.scheduler.core\\src\\main\\java\\avoking\\com\\documentos\\scheduler\\startup\\SplashScreen reducida.png", null, 10000);
    //        s.setVisible(true);
    //      //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    try {//from w w w .j a v  a  2s .c om
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception ex) {
        java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>  

    try {
        FileInputStream fis = new FileInputStream(
                "E:\\Avo-King\\Documentos\\Desarrollo\\PROCEDIMIENTO_Pruebas_RH\\PDRH-05.docx");
        XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(xdoc);
        //read header
        XWPFHeader header = policy.getDefaultHeader();
        System.out.println(StringEscapeUtils.escapeJava(header.getText()));
        //            //read footer
        //            XWPFFooter footer = policy.getDefaultFooter();
        //            System.out.println(footer.getText());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    //        Main m = new Main();
    //        m.execute();
    //        splashLoading.getContentPane().setBackground(Color.WHITE);
    //        splashLoading.pnlProgress.setBackground(Color.WHITE);
    //        splashLoading.setLocationRelativeTo(null);
    //        splashLoading.setVisible(true);
}

From source file:b01.officeLink.ExtendedWordDocument.java

License:Apache License

public ExtendedWordDocument(InputStream istream) throws IOException {
    try {//from  w w w  . j a v a  2 s  .  c o  m
        xwpfDocument = new XWPFDocument(istream);
    } catch (Exception e) {
        xwpfDocument = null;
        Globals.logString("Could not read EXCEL file as xlsx\n" + (e != null ? e.getMessage() : ""));
        try {
            hwpfDocument = new HWPFDocument(istream);
        } catch (Exception e1) {
            hwpfDocument = null;
            Globals.logException(e1);
        }
    }
}

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

License:Apache License

public XWPFDocument getDocument(InputStream inDocument) {

    try {//from   w w w  .  j a  va  2 s  . c om
        XWPFDocument dxReturn = new XWPFDocument(inDocument);
        return dxReturn;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:biz.webgate.dominoext.poi.util.POILibUtil.java

License:Apache License

public static XWPFDocument getDocument(InputStream inDocument) {
    XWPFDocument dxReturn = null;/*from   www.  j  av  a 2s  .  c o m*/
    try {
        dxReturn = new XWPFDocument(inDocument);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dxReturn;
}

From source file:br.gov.lexml.parser.documentoarticulado.LexMLParserFromTextTest.java

License:Open Source License

private String sampleDocx(String resourceName) {
    String content = null;//from w  ww. j  a  v a2  s.  c o  m
    try {
        InputStream input = new BOMInputStream(TestUtil.class.getResourceAsStream(resourceName));
        XWPFDocument document = new XWPFDocument(OPCPackage.open(input));
        @SuppressWarnings("resource")
        XWPFWordExtractor wordExtractor = new XWPFWordExtractor(document);
        content = wordExtractor.getText();
    } catch (Exception exep) {
        exep.printStackTrace();
    }
    return content;
}

From source file:by.creepid.docsreporter.converter.PoiConverterAdapter.java

private XWPFDocument createDocument(InputStream in) throws IOException {
    return new XWPFDocument(in);
}