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

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

Introduction

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

Prototype

@SuppressWarnings("resource")
public final void write(OutputStream stream) throws IOException 

Source Link

Document

Write out this document to an Outputstream.

Usage

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

@Override
public void actionPerformed(ActionEvent e) {
    resultChanged(null);/*from   www .j  av  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: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 v a 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:fr.univrouen.poste.services.WordParser.java

License:Apache License

public void modifyWord(InputStream docx, Map<String, String> textMap, OutputStream out) {
    try {/*  w  w w  . j  a  va 2 s .co  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);
    }

}

From source file:gob.osinergmin.inpsweb.service.business.impl.PlantillaResultadoServiceNegImpl.java

@Override
public DocumentoAdjuntoDTO generaDocumentoPlantilla(Long idPlantillaResultado, Long idSupervision)
        throws PlantillaResultadoException {
    DocumentoAdjuntoDTO retorno = null;//from  w  ww  .  j  a va 2  s  .c  o m
    try {
        PlantillaResultadoDTO plantilla = plantillaResultadoDAO.getPlantillaResultado(idPlantillaResultado);
        LOG.info("nombrePlantilla:" + plantilla.getNombreDocumento());
        LOG.info("identificadorPlantilla:" + plantilla.getIdentificadorPlantilla());
        //obteniendo plantilla con POI
        XWPFDocument document = armarPlantilla(plantilla, idSupervision);
        //Generando Byte[] para salida desde XWPFDocument
        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        document.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        //seteando retorno
        retorno = new DocumentoAdjuntoDTO();
        retorno.setArchivoAdjunto(outArray);
        retorno.setNombreArchivo(plantilla.getNombreDocumento().substring(0,
                plantilla.getNombreDocumento().lastIndexOf("."))
                + new SimpleDateFormat("_yyyyMMdd_hhmmss").format(new Date())
                + plantilla.getNombreDocumento().substring(plantilla.getNombreDocumento().lastIndexOf(".")));
    } catch (Exception e) {
        LOG.error("Error en generaDocumentoPlantilla", e);
        throw new PlantillaResultadoException(e.getMessage(), e);
    }
    return retorno;
}

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 {/* w  w w .  j a va  2s  .  com*/
            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  a2 s  . 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:javaapplication1.AnotherPOI.java

public static void replaceText(String findText, String replaceText) {
    try {/*from w  w w .j  av a 2  s . co  m*/
        XWPFDocument doc = new XWPFDocument(OPCPackage.open("D:\\template.docx"));
        for (XWPFParagraph p : doc.getParagraphs()) {

            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                for (XWPFRun r : runs) {
                    String text = r.getText(0);
                    if (text != null && text.contains(findText)) {
                        text = text.replace(findText, replaceText);
                        r.setText(text, 0);
                    }
                }
            }
        }
        for (XWPFTable tbl : doc.getTables()) {
            for (XWPFTableRow row : tbl.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph p : cell.getParagraphs()) {
                        for (XWPFRun r : p.getRuns()) {
                            String text = r.getText(0);
                            if (text.contains(findText)) {
                                text = text.replace(findText, replaceText);
                                r.setText(text);
                            }
                        }
                    }
                }
            }
        }
        doc.write(new FileOutputStream("D:\\result.docx"));
    } catch (IOException ex) {
        Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidFormatException ex) {
        Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:library.Form_Library.java

private void btPrintReaderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPrintReaderActionPerformed
    try {/*from   w w w. j  a  v a2s.  c o m*/
        // 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

public void PrintBook(BooksFrame booksFrame, Book book, Account _account) {
    try {//w  ww.  j  ava2  s  . c  o m
        XWPFDocument document = new XWPFDocument();
        File file = new File("Sch " + book.getIdCode() + ".doc");
        if (file.exists()) {
            file.createNewFile();
        }

        FileOutputStream out = new FileOutputStream(file);

        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun run;
        BookViewModel bookView = new BookViewModel(book);

        /////////////////
        run = createFieldRun(paragraph, "THNG TIN S?CH");
        run.setFontSize(24);

        paragraph = createPrintInformation(document, _account);
        paragraph = createBookProductInformation(document, bookView);
        paragraph = createBookInformation(document, bookView);

        document.write(out);
        out.close();

        if (Desktop.isDesktopSupported()) {
            Desktop.getDesktop().open(file);
        }

        JOptionPane
                .showMessageDialog(booksFrame,
                        "Xut file " + file.getName() + " thnh cng" + '\n' + "Ti v tr: "
                                + file.getAbsolutePath(),
                        "In thng tin Sch", JOptionPane.INFORMATION_MESSAGE);

    } catch (Exception e) {
        System.out.println(e);

        JOptionPane.showMessageDialog(booksFrame,
                "Xut file tht bi." + '\n' + "Vui lng ng ca s ang s dng file",
                "In thng tin Sch", JOptionPane.WARNING_MESSAGE);
    }

}

From source file:MainPackage.Controllers.OrderController.java

public void Print(Frame frame, Orders order, Account _account) {
    try {/*  w  w w  .jav  a  2 s  .  c  o m*/
        XWPFDocument document = new XWPFDocument();
        File file = new File("Ha n " + order.getIdCode() + ".doc");
        if (file.exists()) {
            file.createNewFile();
        }

        FileOutputStream out = new FileOutputStream(file);

        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun run;
        //            BookViewModel bookView = new BookViewModel(book);

        /////////////////
        run = createFieldRun(paragraph, "CHI TIT HA ?N");
        run.setFontSize(24);

        paragraph = createPrintInformation(document, _account);
        paragraph = createBookProductInformation(document, order);
        paragraph = createBookInformation(document, order);

        //create table
        XWPFTable table = document.createTable();
        setTableAlignment(table, STJc.CENTER);
        table.setCellMargins(50, 50, 50, 50);
        table.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE, 10, 10, "");
        table.setInsideVBorder(XWPFTable.XWPFBorderType.NONE, 20, 20, "");
        //create first row
        XWPFTableRow row = table.getRow(0);
        row.setHeight(40);
        row.getCell(0).setText("STT");
        row.addNewTableCell().setText("M Sn phm");
        row.addNewTableCell().setText("Tn Sn phm");
        row.addNewTableCell().setText("?n v");
        row.addNewTableCell().setText("S lng");
        row.addNewTableCell().setText("Gi ti?n");
        row.addNewTableCell().setText("Thnh ti?n");

        List<OrderLine> list = (List<OrderLine>) order.getOrderLineCollection();
        for (int i = 0; i < list.size(); i++) {
            OrderLine line = list.get(i);

            row = table.createRow();
            row.getCell(0).setText((i + 1) + "");
            row.getCell(1).setText(line.getProductId().getIdCode());
            row.getCell(2).setText(line.getProductId().getName());
            row.getCell(3).setText("Quyn     ");
            row.getCell(4).setText(line.getQuantity() + "     ");
            row.getCell(5).setText(IntToVND(line.getUnitPrice()) + "     ");
            row.getCell(6).setText(IntToVND(line.getTotalPrice()) + "     ");
        }

        document.write(out);
        out.close();

        if (Desktop.isDesktopSupported()) {
            Desktop.getDesktop().open(file);
        }

        JOptionPane
                .showMessageDialog(frame,
                        "Xut file " + file.getName() + " thnh cng" + '\n' + "Ti v tr: "
                                + file.getAbsolutePath(),
                        "In thng tin Ha n", JOptionPane.INFORMATION_MESSAGE);

    } catch (Exception e) {
        System.out.println(e);

        JOptionPane.showMessageDialog(frame,
                "Xut file tht bi." + '\n' + "Vui lng ng ca s ang s dng file",
                "In thng tin Ha n", JOptionPane.WARNING_MESSAGE);
    }
}