Example usage for org.apache.poi.xwpf.usermodel XWPFParagraph createRun

List of usage examples for org.apache.poi.xwpf.usermodel XWPFParagraph createRun

Introduction

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

Prototype

public XWPFRun createRun() 

Source Link

Document

Appends a new run to this paragraph

Usage

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);//  ww  w.j  a  va  2s.  c  o m
        } 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 {/*  w ww. jav  a2s . c om*/
        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);
    }

}

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 w w w  .  ja  v  a 2 s.c  om
            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());
            }
        }
    }

}

From source file:isizulu_spellchecker.Spellchecker.java

private void saveAsAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAsAsActionPerformed
    // TODO add your handling code here:
    int returnVal = fileChooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        try {//from w w  w  . j  av  a2s.  c  o  m
            // 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());
        }
    }
}

From source file:library.Form_Library.java

private void btPrintReaderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPrintReaderActionPerformed
    try {//from  w  w w  . ja  va  2 s.com
        // TODO add your handling code here:
        FileOutputStream fos = new FileOutputStream(tfID.getText() + " - " + tfName.getText() + ".docx");
        XWPFDocument doc = new XWPFDocument();
        XWPFParagraph paraTit = doc.createParagraph();
        paraTit.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun paraTitRun = paraTit.createRun();
        paraTitRun.setBold(true);
        paraTitRun.setText("Reader Information");
        paraTitRun.setFontFamily("Times New Roman");
        paraTitRun.setFontSize(20);
        String content = this.taPrintReader.getText();
        XWPFRun paraTitRun2 = doc.createParagraph().createRun();
        paraTitRun2.setFontFamily("Times New Roman");
        paraTitRun2.setFontSize(16);
        if (content.contains("\n")) {
            String[] lines = content.split("\n");
            paraTitRun2.setText(lines[0], 0); // set first line into XWPFRun
            for (int i = 1; i < lines.length; i++) {
                // add break and insert new text
                paraTitRun2.addBreak();
                paraTitRun2.setText(lines[i]);
            }
        } else {
            paraTitRun2.setText(content, 0);
        }
        doc.write(fos);
        fos.close();
        JOptionPane.showMessageDialog(null, "The document created successfully!!");
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, ex);
    }
}

From source file:MainPackage.Controllers.BookController.java

private XWPFRun createRun(XWPFParagraph paragraph, String text) {
    XWPFRun run;// ww  w .  j a  v  a 2 s . c o m
    run = paragraph.createRun();
    run.setText(text);
    run.addTab();
    return run;
}

From source file:Management.Projects.java

public String CrearMinuta(String datos[], int idProject, String[] Asistentes, String[] puntos)
        throws IOException {
    String result = "";
    ArrayList<XWPFParagraph> listfecha = new ArrayList<>();
    ArrayList<XWPFParagraph> listasistentes = new ArrayList<>();
    ArrayList<XWPFParagraph> listpuntos = new ArrayList<>();
    XWPFDocument doc = new XWPFDocument();
    int i;/* w ww. j a v  a  2 s . co m*/
    XWPFParagraph p3;
    XWPFParagraph p1 = doc.createParagraph();
    p1.setAlignment(ParagraphAlignment.CENTER);
    p1.setBorderBottom(Borders.DOUBLE);
    p1.setBorderTop(Borders.DOUBLE);
    XWPFRun r1 = p1.createRun();
    r1.setBold(true);
    r1.setText("Datos de la minuta");
    r1.setBold(true);
    for (i = 0; i < datos.length; i++) {
        p3 = doc.createParagraph();
        listfecha.add(p3);

    }
    i = 0;
    for (XWPFParagraph para : listfecha) {
        XWPFRun r2 = para.createRun();
        r2.setText(datos[i]);
        r2.setFontSize(20);
        i++;
    }

    XWPFParagraph parrafoAsistentes = doc.createParagraph();
    parrafoAsistentes.setAlignment(ParagraphAlignment.CENTER);
    parrafoAsistentes.setBorderBottom(Borders.DOUBLE);
    parrafoAsistentes.setBorderTop(Borders.DOUBLE);
    XWPFRun r2 = parrafoAsistentes.createRun();
    r2.setBold(true);
    r2.setText("Asistentes:");
    r2.setBold(true);

    XWPFParagraph p4;
    for (i = 0; i < Asistentes.length; i++) {
        p4 = doc.createParagraph();
        listasistentes.add(p4);

    }

    i = 0;
    for (XWPFParagraph para : listasistentes) {
        XWPFRun r3 = para.createRun();
        r3.setText(Asistentes[i]);
        r3.setFontSize(20);
        i++;
    }

    XWPFParagraph parrafoPuntos = doc.createParagraph();
    parrafoPuntos.setAlignment(ParagraphAlignment.CENTER);
    parrafoPuntos.setBorderBottom(Borders.DOUBLE);
    parrafoPuntos.setBorderTop(Borders.DOUBLE);
    XWPFRun r3 = parrafoPuntos.createRun();
    r3.setBold(true);
    r3.setText("Puntos a Tratar:");
    r3.setBold(true);

    XWPFParagraph p5;
    for (i = 0; i < puntos.length; i++) {
        p5 = doc.createParagraph();
        listpuntos.add(p5);

    }
    i = 0;
    for (XWPFParagraph para : listpuntos) {
        XWPFRun r4 = para.createRun();
        r4.setText(puntos[i]);
        r4.setFontSize(20);
        i++;
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(System.getProperty("user.home")
                + "/Documents/NetBeansProjects/StickMaps/web/Minutas/Minuta" + idProject + ".docx");
    } catch (FileNotFoundException ex) {
        System.out.println(ex.toString());
        return ex.toString();
    }
    doc.write(out);
    result = "bien";
    out.close();

    return result;
}

From source file:Management.PruebaDoc.java

public static void main(String[] args) throws IOException {

    XWPFDocument doc = new XWPFDocument();

    XWPFParagraph p3 = doc.createParagraph();
    XWPFRun r4 = p3.createRun();
    r4.setTextPosition(20);/*from  w w w.  ja v  a2s .c o  m*/
    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);

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(
                "C:\\Users\\hilsierivan\\Documents\\NetBeansProjects\\StickMaps\\web\\MapImages\\simple.docx");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(PruebaDoc.class.getName()).log(Level.SEVERE, null, ex);
    }
    doc.write(out);
    out.close();

}

From source file:Modelo.EscribirWord.java

public void cambiarLogo() throws FileNotFoundException, IOException, InvalidFormatException, Exception {

    //ASPOSE//from   w  w w.  j a v  a 2  s .  c  om
    //    Document doc = new Document("HojaInventarioObjeto.doc");
    ////    doc.save("Out.pdf");

    //        HWPFDocument doc = new HWPFDocument(new FileInputStream("HojaInventarioTemplate.doc"));

    XWPFDocument document = new XWPFDocument(new FileInputStream("HojaInventarioTemplate.docx"));
    String imageOldName = "logo";
    try {
        //            LOG.info("replaceImage: old=" + "logo" + ", new=" + "imagePathNew");
        String imagePathNew = "PlayStation_1_Logo.png";

        int newImageWidth = 1;
        int newImageHeight = 2;

        int imageParagraphPos = -1;
        XWPFParagraph imageParagraph = null;

        List<IBodyElement> documentElements = document.getBodyElements();
        for (IBodyElement documentElement : documentElements) {
            imageParagraphPos++;
            if (documentElement instanceof XWPFParagraph) {
                imageParagraph = (XWPFParagraph) documentElement;
                if (imageParagraph != null && imageParagraph.getCTP() != null
                        && imageParagraph.getCTP().toString().trim().indexOf(imageOldName) != -1) {
                    break;
                }
            }
        }

        if (imageParagraph == null) {
            throw new Exception("Unable to replace image data due to the exception:\n" + "'" + imageOldName
                    + "' not found in in document.");
        }
        ParagraphAlignment oldImageAlignment = imageParagraph.getAlignment();

        // remove old image
        document.removeBodyElement(imageParagraphPos - 1);

        // now add new image

        // BELOW LINE WILL CREATE AN IMAGE
        // PARAGRAPH AT THE END OF THE DOCUMENT.
        // REMOVE THIS IMAGE PARAGRAPH AFTER 
        // SETTING THE NEW IMAGE AT THE OLD IMAGE POSITION
        XWPFParagraph newImageParagraph = document.createParagraph();
        XWPFRun newImageRun = newImageParagraph.createRun();
        //newImageRun.setText(newImageText);
        newImageParagraph.setAlignment(oldImageAlignment);

        try (FileInputStream is = new FileInputStream(imagePathNew)) {
            newImageRun.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imagePathNew, Units.toEMU(newImageWidth),
                    Units.toEMU(newImageHeight));
        }

        // set new image at the old image position
        document.setParagraph(newImageParagraph, imageParagraphPos);

        // NOW REMOVE REDUNDANT IMAGE FORM THE END OF DOCUMENT
        document.removeBodyElement(document.getBodyElements().size() - 1);

        //            return document;
    } catch (Exception e) {
        throw new Exception("Unable to replace image '" + imageOldName + "' due to the exception:\n" + e);
    } finally {
        // cleanup code
    }

}

From source file:msoffice.ReadWord.java

public static void main(String[] args) {

    try {//  ww  w  .j av  a  2s  .c  o m
        FileInputStream fis = new FileInputStream("H:\\OFICIOTEMPLATE.docx");
        XWPFDocument docx = new XWPFDocument(fis);

        List<XWPFParagraph> paragraphList = docx.getParagraphs();
        int nump = paragraphList.size();
        System.out.println(nump);

        for (int x = 0; x < paragraphList.size(); x++) {

        }

        for (XWPFParagraph paragraph : paragraphList) {

            String text = paragraph.getText();

            XWPFRun rh = paragraph.createRun();

            if (text.contains("unidad")) {
                text = text.replace("unidad", "CICTE/W-6.a/02.00");
                paragraph.removeRun(8);
                rh.setText(text);

            }
            if (text.contains("receptor")) {
                text = text.replace("receptor",
                        "Gral Brig Jefe del Servicio de Material de Guerra del Ejrcito");

            }

            if (text.contains("asunto")) {
                text = text.replace("asunto", "Sobre articulo de MG (Armamento) y apoyo de elemento tecnico.");

            }

            if (text.contains("referencia")) {
                text = text.replace("referencia", "Oficio N289/CICTE del 01 julio de 2015.");

            }

            if (text.contains("cuerpo")) {
                text = text.replace("cuerpo",
                        "Tengo el honor de dirigirme a Ud., para manifestarle que en relacin a la solicitud de prestamo de una (01) ametralladora BROWNING Cal .50 y la participacin del elemento tcnico Tco 2da MAM Pacheco Tejada Henry, para las pruebas del vehculo blindado OTORONGO, las cuales se han suspendido y sern reprogramadas.\n"
                                + "Asimismo, se informar de manera oportuna la fecha de realizacin de las pruebas del vehculo blindado OTORONGO, para poder contar con artculo de MG (Armamento) y apoyo de elemento tcnico solicitado.\n"
                                + "Hago propicia la oportunidad para expresarle a Ud. los sentimientos de mi especial consideracin y estima personal.");

            }

            System.out.println(text);
            docx.write(new FileOutputStream("OFICIO.docx"));
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}