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

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

Introduction

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

Prototype

public XWPFParagraph createParagraph() 

Source Link

Document

Appends a new paragraph to this document

Usage

From source file:editordetext.IO.java

public void save(String txt) {
    if (!path.equals("")) {
        switch (fileType) {
        case "txt":
            ArrayList<String> lines = new ArrayList();
            Path file = Paths.get(path);
            lines.add(txt);//from   w w w .j a  va  2 s.c om
            try {
                Files.write(file, lines, Charset.forName("UTF-8"));
            } catch (IOException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
            break;
        case "Word":
            XWPFDocument document = new XWPFDocument();
            try {
                FileOutputStream out = new FileOutputStream(new File(path));
                XWPFParagraph paragraph = document.createParagraph();
                XWPFRun run = paragraph.createRun();
                run.setText(txt);
                document.write(out);
                out.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
            break;
        case "PDF":
            try {
                Document pdf = new Document();
                PdfWriter.getInstance(pdf, new FileOutputStream(path));
                pdf.open();
                pdf.add(new Paragraph(txt));
                pdf.close();
            } catch (DocumentException | FileNotFoundException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
            break;
        }
    } else {
        new Save().setVisible(true);
    }
}

From source file:editordetext.IO.java

public void save(String txt, String path) {
    System.out.println(path);/*from w  w  w.j  a v a2 s .  c  o  m*/
    if (!path.equals("")) {
        switch (fileType) {
        case "txt":
            ArrayList<String> lines = new ArrayList();
            Path file = Paths.get(path);
            lines.add(txt);
            try {
                Files.write(file, lines, Charset.forName("UTF-8"));
            } catch (IOException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
            break;
        case "Word":
            XWPFDocument document = new XWPFDocument();
            try {
                FileOutputStream out = new FileOutputStream(new File(path));
                XWPFParagraph paragraph = document.createParagraph();
                XWPFRun run = paragraph.createRun();
                run.setText(txt);
                document.write(out);
                out.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
            break;
        case "PDF":
            try {
                Document pdf = new Document();
                PdfWriter.getInstance(pdf, new FileOutputStream(path));
                pdf.open();
                pdf.add(new Paragraph(txt));
                pdf.close();
            } catch (DocumentException | FileNotFoundException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
            break;
        }
    } else {
        new Save().setVisible(true);
    }
}

From source file:edu.cqupt.test.SimpleDocument.java

License:Apache License

public static void main(String[] args) throws Exception {
    XWPFDocument doc = new XWPFDocument();

    XWPFParagraph p1 = doc.createParagraph();
    p1.setAlignment(ParagraphAlignment.CENTER);
    p1.setBorderBottom(Borders.DOUBLE);/* w ww  . j a  v a2 s.co  m*/
    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("??? " + "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("F://simple.docx");
    doc.write(out);
    out.close();

}

From source file:eremeykin.pete.reports.ui.ReportAction.java

@Override
public void actionPerformed(ActionEvent e) {
    resultChanged(null);// www . j  a  v  a  2  s  .  c om
    if (model == null) {
        return;
    }

    XWPFDocument doc = new XWPFDocument();

    XWPFParagraph p1 = doc.createParagraph();
    p1.setAlignment(ParagraphAlignment.CENTER);
    p1.setVerticalAlignment(TextAlignment.TOP);

    XWPFRun r1 = p1.createRun();
    r1.setBold(true);
    r1.setText("");
    r1.setBold(true);
    r1.setFontFamily("Times New Roman");
    r1.setFontSize(24);
    r1.setTextPosition(10);

    XWPFParagraph p2 = doc.createParagraph();
    p2.setAlignment(ParagraphAlignment.LEFT);
    p2.setVerticalAlignment(TextAlignment.CENTER);
    XWPFRun r2 = p2.createRun();
    r2.setText(" ? : ");
    r2.setBold(false);
    r2.setFontFamily("Times New Roman");
    r2.setFontSize(14);
    r2.setTextPosition(10);

    XWPFTable table = doc.createTable(1, 2);
    table.getCTTbl().addNewTblPr().addNewTblW().setW(BigInteger.valueOf(9000));
    ModelParameter root = model.getRoot();

    int row = 1;
    Map.Entry<ModelParameter, Integer> kv = model.getParameterAndLevelByID(root, 0);
    ModelParameter parameter = kv.getKey();
    Integer level = kv.getValue();

    ArrayList<Integer> ids = new ArrayList(model.asMap().keySet());
    Collections.sort(ids);
    for (Integer each : ids) {
        table.createRow();
        String text = "";
        kv = model.getParameterAndLevelByID(root, each);
        parameter = kv.getKey();
        level = kv.getValue();
        for (int c = 0; c < level; c++) {
            text += "        ";
        }
        table.getRow(row - 1).getCell(0).setText(text + parameter.toString());
        table.getRow(row - 1).getCell(1).setText(parameter.getValue());
        row++;
    }
    table.setWidth(80);

    XWPFParagraph p3 = doc.createParagraph();
    p3.setAlignment(ParagraphAlignment.LEFT);
    p3.setVerticalAlignment(TextAlignment.CENTER);
    XWPFRun r3 = p3.createRun();
    r3.addBreak();
    r3.setText("\n : ");
    r3.setBold(false);
    r3.setFontFamily("Times New Roman");
    r3.setFontSize(14);

    File uPlotFile = new File(WorkspaceManager.INSTANCE.getWorkspace().getAbsolutePath() + "/uplot.png");
    try {
        byte[] picbytes = IOUtils.toByteArray(new FileInputStream(uPlotFile));
        doc.addPictureData(picbytes, XWPFDocument.PICTURE_TYPE_PNG);
        XWPFRun pr = doc.createParagraph().createRun();
        pr.addPicture(new FileInputStream(uPlotFile), Document.PICTURE_TYPE_PNG, "plot.png", Units.toEMU(450),
                Units.toEMU(337));
        pr.addCarriageReturn();
        pr.addBreak(BreakType.PAGE);
        pr.addBreak(BreakType.TEXT_WRAPPING);

    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }

    XWPFParagraph p4 = doc.createParagraph();
    p4.setAlignment(ParagraphAlignment.LEFT);
    p4.setVerticalAlignment(TextAlignment.CENTER);
    XWPFRun r4 = p4.createRun();
    r4.addBreak();
    r4.setText("\n ?: ");
    r4.setBold(false);
    r4.setFontFamily("Times New Roman");
    r4.setFontSize(14);

    File sPlotFile = new File(WorkspaceManager.INSTANCE.getWorkspace().getAbsolutePath() + "/splot.png");
    try {
        byte[] picbytes = IOUtils.toByteArray(new FileInputStream(sPlotFile));
        doc.addPictureData(picbytes, XWPFDocument.PICTURE_TYPE_PNG);
        XWPFParagraph pp = doc.createParagraph();
        pp.createRun().addPicture(new FileInputStream(sPlotFile), Document.PICTURE_TYPE_PNG, "plot.png",
                Units.toEMU(450), Units.toEMU(337));
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }

    File reportFile = new File("report.docx");
    try (FileOutputStream out = new FileOutputStream(reportFile)) {
        doc.write(out);
        if (Desktop.isDesktopSupported()) {
            Desktop.getDesktop().edit(reportFile);
        } else {
        }

    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:export.PageFunctionalRequirements.java

public static void createPage(XWPFDocument document, List<FunctionalRequirement> aux) {
    String nomeProjecto = "(Nome do Projecto)";

    XWPFParagraph paragraph0 = document.createParagraph();
    paragraph0.setPageBreak(true);/*from w ww .j  a v a  2s. c  o  m*/

    XWPFParagraph paragraphTitle1 = document.createParagraph();
    JavaPoi.setTitleStyle(paragraphTitle1, "Requisitos Funcionais");

    XWPFParagraph paragraphOne = document.createParagraph();

    String textRun = "Neste captulo identifica-se o conjunto de requisitos que suportam a actividade "
            + "de gesto e de desenvolvimento da soluo. A sua especificao permite  equipa de desenvolvimento "
            + "do projecto perceber claramente o qu e como implementar as funcionalidades solicitadas pelo cliente.";
    JavaPoi.setBodyStyle(paragraphOne, textRun);

    textRun = "Um requisito traduz uma necessidade identificada pelo cliente que deve ser satisfeita pela soluo a implementar.";
    JavaPoi.setBodyStyle(paragraphOne, textRun);

    textRun = "Os requisitos funcionais traduzem o conjunto de funcionalidades esperadas da soluo, e a sua especificao define a o comportamento desejado da aplicao face  interaco do utilizador.";
    XWPFRun paragraphOneRun3 = JavaPoi.setBodyStyle(paragraphOne, textRun);
    paragraphOneRun3.addCarriageReturn();

    XWPFParagraph paragraphSubtitle1 = document.createParagraph();
    JavaPoi.setSubtitleStyle(paragraphSubtitle1, "Lista de requisitos funcionais");

    XWPFParagraph paragraph2 = document.createParagraph();
    textRun = "O mbito da soluo  constitudo pelos seguintes requisitos funcionais identificados durante o processo de anlise de requisitos.";
    JavaPoi.setBodyStyle(paragraph2, textRun);

    listFunctionalRequirements(document.createParagraph(), aux);

    XWPFParagraph paragraphSubtitle2 = document.createParagraph();
    JavaPoi.setSubtitleStyle(paragraphSubtitle2, "Especificao de requisitos funcionais");

    XWPFParagraph paragraph3 = document.createParagraph();
    textRun = "Nesta seco especifica-se detalhadamente cada requisito funcional da soluo "
            + nomeProjecto + " a desenvolver.";
    JavaPoi.setBodyStyle(paragraph3, textRun);

    //List<FunctionalRequirement>
    /*FunctionalRequirement
     private String name;
     private String description;
     private String reason;
     private String source;
     private String avaliationCriteria;
     private BigInteger clientPriority;
     private BigInteger clientInsatisfaction;
     private BigInteger requirementState;
     private BigInteger version;
     */

    TableFunctionalReq.createAllReqFuncTable(document, aux);

}

From source file:export.PageNonFunctionalReq.java

public void createUsubilidade(XWPFDocument document) {
    XWPFParagraph paragraph0 = document.createParagraph();
    paragraph0.setPageBreak(true);//from   w  w  w .j  a va  2 s. com

    JavaPoi.setTitleStyle(document.createParagraph(), "Requisitos No Funcionais");

    String textRun = "Os requisitos no funcionais so requisitos que declaram restries, ou atributos de qualidade para um software e/ou para o processo de desenvolvimento do sistema. Definem-se nesta seco os requisitos no funcionais que caracterizam a soluo a implementar.";
    JavaPoi.setBodyStyle(document.createParagraph(), textRun).addCarriageReturn();

    JavaPoi.setSubtitleStyle(document.createParagraph(), "Requisitos de Usabilidade");

    textRun = "Os requisitos de usabilidade para a soluo baseiam-se em princpios "
            + "de facilidade de utilizao, compreenso da informao, e numa "
            + "aprendizagem rpida e intuitiva do seu funcionamento por parte dos "
            + "utilizadores finais. A aplicao fornece mecanismos de feedback das "
            + "operaes que o utilizador est a realizar, bem como o estado dessas "
            + "operaes. A aplicao deve promover uma boa navegabilidade, tendo como "
            + "base as 10 heursticas de Jakob Nielsen definidas na Engenharia de " + "Usabilidade.";
    JavaPoi.setBodyStyle(document.createParagraph(), textRun).addCarriageReturn();

    ArrayList<NonFunctionalRequirement> listNFR = new ArrayList<>();
    for (int i = 0; i < 6; i++) {
        NonFunctionalRequirement x = new NonFunctionalRequirement(BigDecimal.valueOf(i), BigInteger.valueOf(5),
                "NF Usabilidade " + i, "textRun", "textRun " + i, "Av textRun " + i, BigInteger.valueOf(1),
                BigInteger.valueOf(1), BigInteger.valueOf(1), BigInteger.valueOf(1));
        listNFR.add(x);
    }

    (new TableNonFunctionalReq()).createAllNonFuncReqTable(document, listNFR);
}

From source file:export.PageNonFunctionalReq.java

public void createInterface(XWPFDocument document) {
    ArrayList<NonFunctionalRequirement> listNFR = new ArrayList<>();
    for (int i = 0; i < 6; i++) {
        NonFunctionalRequirement x = new NonFunctionalRequirement(BigDecimal.valueOf(i), BigInteger.valueOf(1),
                "NF Interface " + i, "textRun", "textRun " + i, "Av textRun " + i, BigInteger.valueOf(1),
                BigInteger.valueOf(1), BigInteger.valueOf(1), BigInteger.valueOf(1));
        listNFR.add(x);/*from  www.  jav  a  2  s .  com*/
    }

    JavaPoi.setSubtitleStyle(document.createParagraph(), "Requisitos de Interface e Imagem");

    (new TableNonFunctionalReq()).createAllNonFuncReqTable(document, listNFR);
}

From source file:export.TableFunctionalReq.java

protected static void createReqFuncTable(XWPFDocument doc, FunctionalRequirement funcReq) {

    int[] cols = { 2943, 6507 };

    XWPFTable rf = doc.createTable(9, 2);

    // Get a list of the rows in the table
    List<XWPFTableRow> rows = rf.getRows();
    int rowCt = 0;
    int colCt = 0;

    for (XWPFTableRow row : rows) {

        // get the cells in this row
        List<XWPFTableCell> cells = row.getTableCells();
        for (XWPFTableCell cell : cells) {
            // get a table cell properties element (tcPr)
            CTTcPr tcpr = cell.getCTTc().addNewTcPr();

            // create cell color element
            CTShd ctshd = tcpr.addNewShd();

            ctshd.setColor("auto");
            ctshd.setVal(STShd.CLEAR);/*w  w w .  java 2  s .  c  o  m*/

            if (colCt == 0) {
                ctshd.setFill("5C7F92");
            }

            // get 1st paragraph in cell's paragraph list
            XWPFParagraph para = cell.getParagraphs().get(0);
            para.setStyle("AltranNormal");
            para.setSpacingAfter(120);
            para.setSpacingBefore(120);

            // create a run to contain the content
            XWPFRun rh = para.createRun();
            //rh.setFontSize(11);

            rh.setFontFamily("Lucida Sans Unicode");

            if (colCt == 0) {
                rh.setColor("FFFFFF");
            }

            if (rowCt == 0 && colCt == 0) {
                rh.setText("RF " + ((x < 9) ? "0" + x : x) + "- F");
                x++;
            } else if (rowCt == 1 && colCt == 0) {
                rh.setText("Use Case (se disponvel):");
            } else if (rowCt == 2 && colCt == 0) {
                rh.setText("Descrio:");
            } else if (rowCt == 3 && colCt == 0) {
                rh.setText("Fonte:");
            } else if (rowCt == 4 && colCt == 0) {
                rh.setText("Fundamento:");
            } else if (rowCt == 5 && colCt == 0) {
                rh.setText("Critrio de avaliao:");
            } else if (rowCt == 6 && colCt == 0) {
                rh.setText("Satisfao do cliente:");
            } else if (rowCt == 7 && colCt == 0) {
                rh.setText("Insatisfao do cliente:");
            } else if (rowCt == 8 && colCt == 0) {
                rh.setText("Histrico:");
            }

            if (rowCt == 0 && colCt == 1) {// Nome do requisito
                rh.setText(funcReq.getName());
                rh.setBold(true);
            } else if (rowCt == 1 && colCt == 1) { // UseCases
                String testUC = "";
                int cntUC = 0;
                for (UseCase uc : funcReq.getUseCaseCollection()) {

                    if (cntUC == 0) {
                        testUC = uc.getName();
                    } else {
                        testUC = testUC + ", " + uc.getName();
                    }
                    cntUC++;
                }

                rh.setText(testUC);
            } else if (rowCt == 2 && colCt == 1) {// Descrio
                rh.setText(funcReq.getDescription());
            } else if (rowCt == 3 && colCt == 1) {// Fonte
                rh.setText(funcReq.getSource());
            } else if (rowCt == 4 && colCt == 1) {// Fundamento
                rh.setText(funcReq.getReason());
            } else if (rowCt == 5 && colCt == 1) {// Criterio de Avalicao
                rh.setText(funcReq.getAvaliationCriteria());
            } else if (rowCt == 6 && colCt == 1) {// Prioridade
                rh.setText(funcReq.getClientPriority().toString());
            } else if (rowCt == 7 && colCt == 1) {// Insatisfao
                rh.setText(funcReq.getClientInsatisfaction().toString());
            } else if (rowCt == 8 && colCt == 1) {// Historico
                rh.setText("Histrico");
            }

            cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(cols[colCt]));
            colCt++;
        }
        colCt = 0;
        rowCt++;

    }

    doc.createParagraph().createRun().addBreak();

}

From source file:FilesHandlers.WordHandler.java

public void changeLine(String docName, int row, String newLine) throws Exception {

    String[] strArr = getDocContentByLine(docName);
    StringBuilder strBuilder = new StringBuilder();

    for (int i = 0; i < strArr.length; i++) {

        if (row == i + 1) {
            System.out.println("s s s s");

            strBuilder.append(newLine);//from  w w  w .j  ava  2  s .c om
        } else {
            strBuilder.append(strArr[i]);
        }
        strBuilder.append("\n");

    }

    String content = strBuilder.toString();

    System.out.println(content);

    // Blank Document
    XWPFDocument document = new XWPFDocument();

    // Write the Document in file system
    FileOutputStream out = new FileOutputStream(new File(workingDirectory.concat(docName)));

    // create Paragraph
    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun run = paragraph.createRun();
    run.setText(content);

    document.write(out);
    out.close();
    System.out.println("It was updated succesfully");
}

From source file:IsiXhosa_spellchecker.Spellchecker.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // Save file being edited to machine
    int len = textArea.getText().length();
    boolean English = jRadioButton1.isSelected();
    if (len == 0) {
        if (English) {
            instruction.setText("You are trying to save an empty file!");
            instruction.setForeground(Color.RED);
        } else {/*from  ww w . j  av a2 s.c o m*/
            instruction.setText("Uzama ukugcina ifayile engenanto!");
            instruction.setForeground(Color.RED);
        }
        //System.out.println(data);
    } else {
        int returnVal = fileChooser.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                // What to do with the file, e.g. display it in a TextArea
                if (highlightSet) {
                    highlighter.removeAllHighlights();
                }
                if (file.getName().endsWith(".docx")) {
                    XWPFDocument document = new XWPFDocument();
                    XWPFParagraph tmpParagraph = document.createParagraph();
                    XWPFRun tmpRun = tmpParagraph.createRun();
                    tmpRun.setText(textArea.getText());
                    tmpRun.setFontSize(12);
                    document.write(new FileOutputStream(new File(file.getPath())));
                } else {
                    textArea.write(new FileWriter(file.getAbsolutePath()));//this file has no extension
                }
            } catch (IOException ex) {
                System.out.println("problem accessing file" + file.getAbsolutePath());
            }
        }
    }

}