Example usage for org.apache.poi.xwpf.usermodel XWPFRun setText

List of usage examples for org.apache.poi.xwpf.usermodel XWPFRun setText

Introduction

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

Prototype

public void setText(String value) 

Source Link

Document

Sets the text of this text run

Usage

From source file:editordetext.IO.java

public void save(String txt, String path) {
    System.out.println(path);//w w w.  j av  a2s  .co  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);//  ww  w  .  j  av  a2 s .c  o  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:edu.gatech.pmase.capstone.awesome.impl.output.DisasterResponseTradeStudyOutputer.java

License:Open Source License

/**
 * Creates the architecture attribute description cell.
 *
 * @param detailsCell the cell to create the description in
 * @param attrs the attributes to put into the description
 *//*  w  w  w  .  j  a  v a2s . c  o  m*/
private void createArchitectureAttributeDescription(final XWPFTableCell detailsCell,
        final List<ArchitectureOptionAttribute> attrs) {

    for (int x = 0; x < attrs.size(); x++) {
        final ArchitectureOptionAttribute attr = attrs.get(x);
        LOGGER.debug("Creating architecture option description for attribute: " + attr.getLabel());

        final XWPFParagraph para;
        if (x == 0) {
            para = detailsCell.getParagraphs().get(0);
        } else {
            para = detailsCell.addParagraph();
        }

        final XWPFRun rh = para.createRun();
        rh.setText(DisasterResponseTradeStudyOutputer.createAttribtueString(attr));
        para.setAlignment(ParagraphAlignment.CENTER);
    }
}

From source file:edu.gatech.pmase.capstone.awesome.impl.output.DisasterResponseTradeStudyOutputer.java

License:Open Source License

/**
 * Creates the report details paragraph.
 *
 * @param xdoc the document to create the paragraph in
 *//*  ww w  . j  a  v a  2s .c  o  m*/
private void createReportDetails(final XWPFDocument xdoc) {
    final Locale currentLocale = Locale.getDefault();
    LOGGER.debug("Creating report details");

    final XWPFParagraph para = xdoc.getParagraphs().get(REPORT_DETAILS_ROW_INDEX);
    final XWPFRun run1 = para.createRun();
    run1.setBold(true);
    run1.setText("Date Report Generated: ");

    final XWPFRun run2 = para.createRun();
    run2.setBold(false);
    run2.setText(outputFileFormatter.format(now));
    run2.addBreak();

    final XWPFRun run3 = para.createRun();
    run3.setBold(true);
    run3.setText("Country Report Generated: ");

    final XWPFRun run4 = para.createRun();
    run4.setBold(false);
    run4.setText(currentLocale.getDisplayCountry());
}

From source file:edu.gatech.pmase.capstone.awesome.impl.output.DisasterResponseTradeStudyOutputer.java

License:Open Source License

/**
 * Creates output for architecture options if no architecture was found.
 *
 * @param label the cell with the label// ww w. j a  va2s.com
 * @param optionName the name of the option to place
 */
private static void createNoOptionText(final XWPFTableCell label, final String optionName) {
    LOGGER.debug("Creationg No Option Text for option: " + optionName);
    final XWPFParagraph platPara = label.getParagraphs().get(0);
    final XWPFRun rh = platPara.createRun();
    rh.setColor(DisasterResponseTradeStudyOutputer.NO_OPT_TEXT_COLOR);
    rh.setText("No " + optionName + " Satisfies Selections");
    platPara.setAlignment(ParagraphAlignment.CENTER);
}

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

@Override
public void actionPerformed(ActionEvent e) {
    resultChanged(null);//w w w.  jav a 2s.c o  m
    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.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 .  ja  v a  2  s  .  co  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:File.DOCX.WriteDocx.java

public void Write(String header, String footer, String kalimat, String alignment, String path) {
    try {/* w w w .  j  a  va 2s .  c  o  m*/

        CreateHeader(header);
        CreateFooter(footer);
        ParagraphAlignment align = null;
        if (alignment.equalsIgnoreCase("left")) {
            align = ParagraphAlignment.LEFT;
        } else if (alignment.equalsIgnoreCase("right")) {
            align = ParagraphAlignment.RIGHT;
        } else if (alignment.equalsIgnoreCase("center")) {
            align = ParagraphAlignment.CENTER;
        }
        //write body content
        String[] split_kalimat = kalimat.split("\n");
        for (String text : split_kalimat) {
            XWPFParagraph bodyParagraph = docx.createParagraph();
            bodyParagraph.setAlignment(align);
            XWPFRun r = bodyParagraph.createRun();
            r.setText(text);
        }

        FileOutputStream out = new FileOutputStream(path);
        docx.write(out);
        out.close();
        System.out.println("Done");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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);//  w w w  . jav  a2  s  .  com
        } 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:fr.univrouen.poste.services.WordParser.java

License:Apache License

public void modifyWord(InputStream docx, Map<String, String> textMap, OutputStream out) {
    try {//from  ww w  . j a  va2s.  c o m
        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);
    }

}