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:org.obeonetwork.m2doc.generator.test.TemplateProcessorTest.java

License:Open Source License

/**
 * Tests a gd:if with <code>false</code> expression evaluation and with an
 * else./*from   www.  j av  a 2 s  .c o m*/
 * 
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 */
@Test
public void testGDIF7Processing() throws InvalidFormatException, IOException, DocumentParserException {
    FileInputStream is = new FileInputStream("templates/testConditionnal5.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    BodyParser parser = new BodyParser(document, env);
    Template template = parser.parseTemplate();
    Map<String, Object> definitions = new HashMap<String, Object>();
    definitions.put("x", "value");
    XWPFDocument destinationDoc = createDestinationDocument("templates/testConditionnal5.docx");
    TemplateProcessor processor = new TemplateProcessor(definitions, "", env, destinationDoc);
    processor.doSwitch(template);
    assertEquals("Template de test pour les balises conditionnelles\u00a0: ajout de default value",
            destinationDoc.getParagraphs().get(0).getText());
}

From source file:org.obeonetwork.m2doc.generator.test.TemplateProcessorTest.java

License:Open Source License

/**
 * Tests a gd:if with <code>false</code> expression evaluation and with an
 * else./*w  w w  . j a  va  2 s  .c om*/
 * 
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 */
@Test
public void testGDIF8Processing() throws InvalidFormatException, IOException, DocumentParserException {
    FileInputStream is = new FileInputStream("templates/testConditionnal6.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    BodyParser parser = new BodyParser(document, env);
    Template template = parser.parseTemplate();
    Map<String, Object> definitions = new HashMap<String, Object>();
    definitions.put("x", "value1");
    XWPFDocument destinationDoc = createDestinationDocument("templates/testConditionnal6.docx");
    TemplateProcessor processor = new TemplateProcessor(definitions, "", env, destinationDoc);
    processor.doSwitch(template);
    assertEquals("Template de test pour les balises conditionnelles\u00a0: ajout de value1",
            destinationDoc.getParagraphs().get(0).getText());
}

From source file:org.obeonetwork.m2doc.generator.test.TemplateProcessorTest.java

License:Open Source License

/**
 * Tests a gd:if with <code>false</code> expression evaluation and with an
 * else.//from ww w .  jav  a2 s  . c  om
 * 
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 */
@Test
public void testCarryageReturnProcessing() throws InvalidFormatException, IOException, DocumentParserException {
    FileInputStream is = new FileInputStream("templates/testCarriageReturn.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    BodyParser parser = new BodyParser(document, env);
    Template template = parser.parseTemplate();
    Map<String, Object> definitions = new HashMap<String, Object>();
    definitions.put("v", "part1\npart2\npart3\npart4");
    XWPFDocument destinationDoc = createDestinationDocument("templates/testCarriageReturn.docx");
    TemplateProcessor processor = new TemplateProcessor(definitions, "", env, destinationDoc);
    processor.doSwitch(template);
    assertEquals(4, destinationDoc.getParagraphs().size());
}

From source file:org.obeonetwork.m2doc.generator.test.TemplateProcessorTest.java

License:Open Source License

/**
 * Tests a gd:if with <code>false</code> expression evaluation and with an
 * else./*  w  ww.  j a v  a 2 s . c o m*/
 * 
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 */
@Test
public void testEmptyParagraphsProcessing()
        throws InvalidFormatException, IOException, DocumentParserException {
    FileInputStream is = new FileInputStream("templates/testEmptyParagraphs.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    BodyParser parser = new BodyParser(document, env);
    Template template = parser.parseTemplate();
    Map<String, Object> definitions = new HashMap<String, Object>();
    definitions.put("author", "Moi");
    XWPFDocument destinationDoc = createDestinationDocument("templates/testEmptyParagraphs.docx");
    TemplateProcessor processor = new TemplateProcessor(definitions, "", env, destinationDoc);
    processor.doSwitch(template);
    assertEquals(5, destinationDoc.getParagraphs().size());
    assertEquals("Paragraph1 Moi", destinationDoc.getParagraphs().get(0).getText());
    assertEquals("", destinationDoc.getParagraphs().get(1).getText());
    assertEquals("Paragraph2", destinationDoc.getParagraphs().get(2).getText());
    assertEquals("", destinationDoc.getParagraphs().get(3).getText());
    assertEquals("Paragraph3 Moi", destinationDoc.getParagraphs().get(4).getText());
}

From source file:org.obeonetwork.m2doc.generator.test.TemplateRuntimeErrorTests.java

License:Open Source License

/**
 * Tests processing of a variable reference where the variable is unknown.
 * /*from  w w w . j  a  v a  2s . com*/
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 */
@Test
public void testUnknownVarRefProcessing() throws InvalidFormatException, IOException, DocumentParserException {
    FileInputStream is = new FileInputStream("templates/testVar.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    BodyParser parser = new BodyParser(document, env);
    Template template = parser.parseTemplate();
    Map<String, Object> definitions = new HashMap<String, Object>();
    XWPFDocument destinationDoc = createDestinationDocument("templates/testVar.docx");
    TemplateProcessor processor = new TemplateProcessor(definitions, "", env, destinationDoc);
    processor.doSwitch(template);
    // scan the destination document
    assertEquals(2, destinationDoc.getParagraphs().size());
    System.out.println(destinationDoc.getParagraphs().get(0).getText());
    assertEquals(
            "Template de test pour les balises de rfrence  une variable\u00a0: Couldn't find the x variable",
            destinationDoc.getParagraphs().get(0).getText());
    XWPFRun run = destinationDoc.getParagraphs().get(0).getRuns()
            .get(destinationDoc.getParagraphs().get(0).getRuns().size() - 1);
    assertEquals("FF0000", run.getColor());
    assertNotNull(run.getCTR().getRPr().getB());

    assertEquals("Fin du gabarit", destinationDoc.getParagraphs().get(1).getText());
}

From source file:org.obeonetwork.m2doc.generator.test.TemplateRuntimeErrorTests.java

License:Open Source License

/**
 * Tests processing of a query where the evaluation results in an error.
 * /*from   w  w w.j  av a2s  .  c  om*/
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 */
@Test
public void testQueryEvaluationErrorProcessing()
        throws InvalidFormatException, IOException, DocumentParserException {
    FileInputStream is = new FileInputStream("templates/testAQL.docx");
    OPCPackage oPackage = OPCPackage.open(is);
    XWPFDocument document = new XWPFDocument(oPackage);
    BodyParser parser = new BodyParser(document, env);
    Template template = parser.parseTemplate();
    Map<String, Object> definitions = new HashMap<String, Object>();
    XWPFDocument destinationDoc = createDestinationDocument("templates/testAQL.docx");
    TemplateProcessor processor = new TemplateProcessor(definitions, "", env, destinationDoc);
    processor.doSwitch(template);
    // scan the destination document
    assertEquals(4, destinationDoc.getParagraphs().size());
    System.out.println(destinationDoc.getParagraphs().get(0).getText());
    assertEquals("Template de test pour les balises de query aql\u00a0: Couldn't find the self variable",
            destinationDoc.getParagraphs().get(0).getText());
    assertEquals(
            "Attempt to access feature (name) on a non ModelObject value (org.eclipse.acceleo.query.runtime.impl.Nothing).",
            destinationDoc.getParagraphs().get(1).getText());
    XWPFRun run = destinationDoc.getParagraphs().get(0).getRuns()
            .get(destinationDoc.getParagraphs().get(0).getRuns().size() - 1);
    assertEquals("FF0000", run.getColor());
    assertNotNull(run.getCTR().getRPr().getB());
    assertEquals("Fin du gabarit", destinationDoc.getParagraphs().get(2).getText());
    assertEquals("", destinationDoc.getParagraphs().get(3).getText());
}

From source file:org.obeonetwork.m2doc.test.M2DocTestUtils.java

License:Open Source License

/**
 * Gets the {@link XWPFRun} containing the given text in the given {@link XWPFDocument}.
 * /* www  .  ja v  a 2s  . c om*/
 * @param document
 *            the {@link XWPFDocument}
 * @param text
 *            the {@link XWPFRun}
 * @return the {@link XWPFRun} containing the given text in the given {@link XWPFDocument} if any, <code>null</code> otherwise
 */
public static XWPFRun getRunContaining(XWPFDocument document, String text) {
    XWPFRun res = null;

    for (XWPFParagraph paragraph : document.getParagraphs()) {
        for (XWPFRun run : paragraph.getRuns()) {
            if (run.text().contains(text)) {
                res = run;
                break;
            }
        }
    }

    return res;
}

From source file:org.shareok.data.documentProcessor.WordHandler.java

private String[] readDocxFile(FileInputStream fs) throws IOException {

    String[] paragraphs = null;//from  w  w  w .  j  av  a  2  s  .  c  om
    try {
        //            XWPFDocument doc = new XWPFDocument();
        //            XWPFParagraph p1 = doc.createParagraph();
        //        p1.setAlignment(ParagraphAlignment.CENTER);
        //        p1.setBorderBottom(Borders.DOUBLE);
        //        p1.setBorderTop(Borders.DOUBLE);
        //
        //        p1.setBorderRight(Borders.DOUBLE);
        //        p1.setBorderLeft(Borders.DOUBLE);
        //        p1.setBorderBetween(Borders.SINGLE);
        //
        //        p1.setVerticalAlignment(TextAlignment.TOP);
        //
        //        XWPFRun r1 = p1.createRun();
        //        r1.setBold(true);
        //        r1.setText("The quick brown fox");
        //        r1.setBold(true);
        //        r1.setFontFamily("Courier");
        //        r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
        //        r1.setTextPosition(100);
        //
        //        XWPFParagraph p2 = doc.createParagraph();
        //        p2.setAlignment(ParagraphAlignment.RIGHT);
        //
        //        //BORDERS
        //        p2.setBorderBottom(Borders.DOUBLE);
        //        p2.setBorderTop(Borders.DOUBLE);
        //        p2.setBorderRight(Borders.DOUBLE);
        //        p2.setBorderLeft(Borders.DOUBLE);
        //        p2.setBorderBetween(Borders.SINGLE);
        //
        //        XWPFRun r2 = p2.createRun();
        //        r2.setText("jumped over the lazy dog");
        //        r2.setStrike(true);
        //        r2.setFontSize(20);
        //
        //        XWPFRun r3 = p2.createRun();
        //        r3.setText("and went away");
        //        r3.setStrike(true);
        //        r3.setFontSize(20);
        //        r3.setSubscript(VerticalAlign.SUPERSCRIPT);
        //
        //
        //        XWPFParagraph p3 = doc.createParagraph();
        //        p3.setWordWrap(true);
        //        p3.setPageBreak(true);
        //                
        //        //p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
        //        p3.setAlignment(ParagraphAlignment.BOTH);
        //        p3.setSpacingLineRule(LineSpacingRule.EXACT);
        //
        //        p3.setIndentationFirstLine(600);
        //        
        //
        //        XWPFRun r4 = p3.createRun();
        //        r4.setTextPosition(20);
        //        r4.setText("To be, or not to be: that is the question: "
        //                + "Whether 'tis nobler in the mind to suffer "
        //                + "The slings and arrows of outrageous fortune, "
        //                + "Or to take arms against a sea of troubles, "
        //                + "And by opposing end them? To die: to sleep; ");
        //        r4.addBreak(BreakType.PAGE);
        //        r4.setText("No more; and by a sleep to say we end "
        //                + "The heart-ache and the thousand natural shocks "
        //                + "That flesh is heir to, 'tis a consummation "
        //                + "Devoutly to be wish'd. To die, to sleep; "
        //                + "To sleep: perchance to dream: ay, there's the rub; "
        //                + ".......");
        //        r4.setItalic(true);
        ////This would imply that this break shall be treated as a simple line break, and break the line after that word:
        //
        //        XWPFRun r5 = p3.createRun();
        //        r5.setTextPosition(-10);
        //        r5.setText("For in that sleep of death what dreams may come");
        //        r5.addCarriageReturn();
        //        r5.setText("When we have shuffled off this mortal coil,"
        //                + "Must give us pause: there's the respect"
        //                + "That makes calamity of so long life;");
        //        r5.addBreak();
        //        r5.setText("For who would bear the whips and scorns of time,"
        //                + "The oppressor's wrong, the proud man's contumely,");
        //        
        //        r5.addBreak(BreakClear.ALL);
        //        r5.setText("The pangs of despised love, the law's delay,"
        //                + "The insolence of office and the spurns" + ".......");
        //
        //        FileOutputStream out = new FileOutputStream("simple.docx");
        //        doc.write(out);
        //        out.close();
        XWPFDocument document = new XWPFDocument(OPCPackage.open("simple.docx"));
        List<XWPFParagraph> paragraphList = document.getParagraphs();
        paragraphs = new String[paragraphList.size()];
        int i = 0;
        for (XWPFParagraph para : paragraphList) {
            paragraphs[i] = para.getText();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        fs.close();
    }
    return paragraphs;
}

From source file:persistentie.PixelMapper.java

public List<String> leesDocFile(String bestandsNaam) {
    List<String> zin = new ArrayList<>();
    letterLijst = new ArrayList<>();
    File file = null;/*  w w  w  .  j a v a  2s .  co  m*/
    XWPFWordExtractor extractor = null;
    try {
        XWPFDocument document = new XWPFDocument(Files.newInputStream(Paths.get(bestandsNaam)));
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph par : paragraphs) {
            /**
             * Elke paragraph op spaties splitten en elk woord in de letterlijst plaatsen.
             */
            zin = Arrays.asList(par.getParagraphText().split(" "));
            for (String woord : zin) {
                letterLijst.add(woord);
                letterLijst.add(" ");
            }
            letterLijst.add("\n");
        }
    } catch (Exception exep) {
        exep.printStackTrace();
    }

    return letterLijst;
}

From source file:service.GenerationLettres.CreerPiecesManquantes.java

/**
* 
* @param filename - Nom du fichier modle de demande des pices manquantes.
* @param idDossier - Identifiant du dossier pour lequel l est cr
* @throws InvalidFormatException/*www  . j a  v a2 s.  c om*/
* @throws IOException 
*/
public void replacePiecesManquantes(String filename, Formation formation, String sexe, String nom,
        String prenom, String adresse, Adresse adresseEntite, List<Justificatif> justificatifsOk)
        throws InvalidFormatException, IOException {
    List<Justificatif> lesJustificatifs = formation.getLesJustificatifs();

    Date dateActuelle = new Date();
    DateFormat dateForm = new SimpleDateFormat("dd MMMM yyyy", Locale.FRANCE);
    String date = dateForm.format(dateActuelle);
    String codePostal = adresseEntite.getCodePostal();
    String ville = adresseEntite.getVille();
    String civilite = "";
    if (sexe.equals("Masculin"))
        civilite = "Monsieur";
    if (sexe.equals("Feminin"))
        civilite = "Madame";

    String intitule = formation.getIntitule();

    if (justificatifsOk != null) {
        for (Justificatif just : justificatifsOk) {
            lesJustificatifs.remove(just);
        }
    }

    String newFileName = nom + prenom + " Lettre piecesManquantes.docx";

    File file = new File(PATH_MODELS + "/" + filename);
    FileInputStream fis = new FileInputStream(file.getAbsolutePath());
    XWPFDocument doc = new XWPFDocument(fis);
    doc.write(new FileOutputStream(PATH_TARGET + "/" + newFileName));
    doc.close();

    doc = new XWPFDocument(OPCPackage.open(PATH_TARGET + "/" + newFileName));

    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$formation")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$formation", intitule);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de la formation effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$date")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$date", date);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de la date effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$civilite")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$civilite", civilite);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de la civilite effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$prenom")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$prenom", prenom);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement du prenom effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$nom")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$nom", nom);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement du nom effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$adresse")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$adresse", adresse);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de l'adresse effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$codePostal")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$codePostal", codePostal);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement du code postal effectue");
        }
    }
    for (XWPFParagraph p : doc.getParagraphs()) {
        int numberOfRuns = p.getRuns().size();
        StringBuilder sb = new StringBuilder();
        for (XWPFRun r : p.getRuns()) {
            int pos = r.getTextPosition();
            if (r.getText(pos) != null) {
                sb.append(r.getText(pos));
            }
        }
        if (sb.length() > 0 && sb.toString().contains("$ville")) {
            for (int i = numberOfRuns - 1; i > 0; i--) {
                p.removeRun(i);
            }
            String text = sb.toString().replace("$ville", ville);
            XWPFRun run = p.getRuns().get(0);
            run.setText(text, 0);
            System.out.println("Changement de la ville effectue");
        }
    }

    XWPFTable table = doc.createTable(lesJustificatifs.size(), 2);
    table.setCellMargins(200, 250, 0, 250);
    int i = 0;
    for (XWPFTableRow r : table.getRows()) {
        XWPFTableCell cell = r.getCell(0);
        cell.setText(lesJustificatifs.get(i).getTitre());
        cell = r.getCell(1);
        cell.setText(lesJustificatifs.get(i).getDescription());
        i++;
    }

    doc.write(new FileOutputStream(PATH_TARGET + "/temp.docx"));
    new File(PATH_TARGET + "/temp.docx").delete();
    doc.close();
    //copyTempToFile(filename);
    System.out.println("replaceLettrePiecesManquantes DONE");
}