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:com.min.word.core.MakeWordFileTest.java

License:Apache License

public static void main(String[] args) throws Exception {
    String fileName = "test.docx";
    System.out.println("---------- Word Create Start ------------");
    //  word ? ?// w w w.j  av  a 2 s .  c om
    XWPFDocument document = new XWPFDocument();
    FileOutputStream out = new FileOutputStream(new File(fileName));
    System.out.println("---------- Create Blank Success ------------");

    //Paragraph ?
    XWPFParagraph paragraph = document.createParagraph();
    System.out.println("---------- Create Paragraph Success ------------");

    //border ?
    paragraph.setBorderBottom(Borders.BASIC_BLACK_DASHES);
    paragraph.setBorderLeft(Borders.BASIC_BLACK_DASHES);
    paragraph.setBorderRight(Borders.BASIC_BLACK_DASHES);
    paragraph.setBorderTop(Borders.BASIC_BLACK_DASHES);
    System.out.println("---------- Create Border Success ------------");

    XWPFRun run = paragraph.createRun();
    run.setText("At tutorialspoint.com, we strive hard to " + "provide quality tutorials for self-learning "
            + "purpose in the domains of Academics, Information "
            + "Technology, Management and Computer Programming Languages.");
    System.out.println("---------- Text Write to File ------------");

    //Table ?
    XWPFTable table = document.createTable();
    //row
    XWPFTableRow rowOne = table.getRow(0);
    rowOne.getCell(0).setText("Col One, Row One");
    rowOne.addNewTableCell().setText("Col Tow, Row One");
    rowOne.addNewTableCell().setText("Col Three, Row One");
    //row
    XWPFTableRow rowTow = table.createRow();
    rowTow.getCell(0).setText("Col One, Row Tow");
    rowTow.getCell(1).setText("Col Tow, Row Tow");
    rowTow.getCell(2).setText("Col Three, Row Tow");
    //row
    XWPFTableRow rowThree = table.createRow();
    rowThree.getCell(0).setText("Col One, Row Three");
    rowThree.getCell(1).setText("Col Tow, Row Three");
    rowThree.getCell(2).setText("Col Three, Row Three");
    System.out.println("---------- Create Table Success ------------");

    //Add Image
    XWPFParagraph imageParagraph = document.createParagraph();
    XWPFRun imageRun = imageParagraph.createRun();
    imageRun.addPicture(new FileInputStream("test.png"), XWPFDocument.PICTURE_TYPE_PNG, "test.png",
            Units.toEMU(300), Units.toEMU(300));
    System.out.println("---------- Create Image Success ------------");

    //Hyperlink
    XWPFParagraph hyperlink = document.createParagraph();
    String id = hyperlink.getDocument().getPackagePart()
            .addExternalRelationship("http://niee.kr", XWPFRelation.HYPERLINK.getRelation()).getId();
    CTR ctr = CTR.Factory.newInstance();
    CTHyperlink ctHyperlink = hyperlink.getCTP().addNewHyperlink();
    ctHyperlink.setId(id);

    CTText ctText = CTText.Factory.newInstance();
    ctText.setStringValue("Hyper-Link TEST");
    ctr.setTArray(new CTText[] { ctText });

    // ???? ?
    CTColor color = CTColor.Factory.newInstance();
    color.setVal("0000FF");
    CTRPr ctrPr = ctr.addNewRPr();
    ctrPr.setColor(color);
    ctrPr.addNewU().setVal(STUnderline.SINGLE);

    // 
    CTFonts fonts = ctrPr.isSetRFonts() ? ctrPr.getRFonts() : ctrPr.addNewRFonts();
    fonts.setAscii("?? ");
    fonts.setEastAsia("?? ");
    fonts.setHAnsi("?? ");

    // ? 
    CTHpsMeasure sz = ctrPr.isSetSz() ? ctrPr.getSz() : ctrPr.addNewSz();
    sz.setVal(new BigInteger("24"));
    ctHyperlink.setRArray(new CTR[] { ctr });
    hyperlink.setAlignment(ParagraphAlignment.LEFT);
    hyperlink.setVerticalAlignment(TextAlignment.CENTER);
    System.out.println("---------- Create Hyperlink Success ------------");

    //Font style
    XWPFParagraph fontStyle = document.createParagraph();

    //set Bold an Italic
    XWPFRun boldAnItalic = fontStyle.createRun();
    boldAnItalic.setBold(true);
    boldAnItalic.setItalic(true);
    boldAnItalic.setText("Bold an Italic");
    boldAnItalic.addBreak();

    //set Text Position
    XWPFRun textPosition = fontStyle.createRun();
    textPosition.setText("Set Text Position");
    textPosition.setTextPosition(100);

    //Set Strike through and font Size and Subscript
    XWPFRun otherStyle = fontStyle.createRun();
    otherStyle.setStrike(true);
    otherStyle.setFontSize(20);
    otherStyle.setSubscript(VerticalAlign.SUBSCRIPT);
    otherStyle.setText(" Set Strike through and font Size and Subscript");
    System.out.println("---------- Set Font Style ------------");

    //Set Alignment Paragraph
    XWPFParagraph alignment = document.createParagraph();
    //Alignment to Right
    alignment.setAlignment(ParagraphAlignment.RIGHT);

    XWPFRun alignRight = alignment.createRun();
    alignRight.setText(
            "At tutorialspoint.com, we strive hard to " + "provide quality tutorials for self-learning "
                    + "purpose in the domains of Academics, Information "
                    + "Technology, Management and Computer Programming " + "Languages.");

    //Alignment to Center
    alignment = document.createParagraph();
    //Alignment to Right
    alignment.setAlignment(ParagraphAlignment.CENTER);
    XWPFRun alignCenter = alignment.createRun();
    alignCenter.setText("The endeavour started by Mohtashim, an AMU "
            + "alumni, who is the founder and the managing director "
            + "of Tutorials Point (I) Pvt. Ltd. He came up with the "
            + "website tutorialspoint.com in year 2006 with the help"
            + "of handpicked freelancers, with an array of tutorials"
            + " for computer programming languages. ");
    System.out.println("---------- Set Alignment ------------");

    //word ? 
    document.write(out);
    out.close();
    System.out.println("---------- Save File Name : " + fileName + " ------------");
    System.out.println("---------- Word Create End ------------");
}

From source file:com.qihang.winter.poi.excel.view.JeecgTemplateWordView.java

License:Apache License

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String codedFileName = ".docx";
    if (model.containsKey(com.qihang.winter.poi.excel.entity.vo.TemplateWordConstants.FILE_NAME)) {
        codedFileName = (String) model
                .get(com.qihang.winter.poi.excel.entity.vo.TemplateWordConstants.FILE_NAME) + ".docx";
    }/*from  w ww . ja  v a 2 s.  c om*/
    if (isIE(request)) {
        codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8");
    } else {
        codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1");
    }
    response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
    XWPFDocument document = com.qihang.winter.poi.word.WordExportUtil.exportWord07(
            (String) model.get(com.qihang.winter.poi.excel.entity.vo.TemplateWordConstants.URL),
            (Map<String, Object>) model
                    .get(com.qihang.winter.poi.excel.entity.vo.TemplateWordConstants.MAP_DATA));
    ServletOutputStream out = response.getOutputStream();
    document.write(out);
    out.flush();
}

From source file:com.siemens.sw360.licenseinfo.outputGenerators.DocxGenerator.java

License:Open Source License

@Override
public byte[] generateOutputFile(Collection<LicenseInfoParsingResult> projectLicenseInfoResults,
        String projectName) throws SW360Exception {
    try {//  w w w.  j a  v  a  2s. c o m
        XWPFDocument document = new XWPFDocument(
                this.getClass().getResourceAsStream("/templateFrontpageContent.docx"));

        fillDocument(document, projectLicenseInfoResults, projectName);

        ByteArrayOutputStream docxOutputStream = new ByteArrayOutputStream();
        document.write(docxOutputStream);
        docxOutputStream.close();
        return docxOutputStream.toByteArray();
    } catch (IOException ioe) {
        throw new SW360Exception("Got IOException when generating docx document: " + ioe.getMessage());
    }
}

From source file:com.simplexwork.mysql.tools.utils.DocumentUtils.java

License:Apache License

/**
 * ??word//from   w  ww  .ja va  2s .c  om
 * 
 * @param tablesMap
 * @throws Exception
 */
public static void productDatabaseDoc(Map<String, TableInfo> tablesMap) throws Exception {
    XWPFDocument xwpfDocument = new XWPFDocument();

    for (Entry<String, TableInfo> entry : tablesMap.entrySet()) {
        TableInfo tableInfo = entry.getValue();

        XWPFParagraph xwpfParagraph = xwpfDocument.createParagraph();
        XWPFRun xwpfRun = xwpfParagraph.createRun();
        xwpfRun.setText(tableInfo.getTableName() + "(" + tableInfo.getTableComment() + ")");
        xwpfRun.setFontSize(18);
        xwpfRun.setTextPosition(10);

        XWPFTable xwpfTable = xwpfDocument.createTable(tableInfo.getColumns().size() + 1, 6);

        int i = 0;

        xwpfTable.getRow(i).getCell(0).setText("??");
        xwpfTable.getRow(i).getCell(1).setText("");
        xwpfTable.getRow(i).getCell(2).setText("");
        xwpfTable.getRow(i).getCell(3).setText("");
        xwpfTable.getRow(i).getCell(4).setText("");
        xwpfTable.getRow(i).getCell(5).setText("?");

        for (Column column : tableInfo.getColumns()) {
            int j = 0;
            i++;
            xwpfTable.getRow(i).getCell(j++).setText(column.getName());
            xwpfTable.getRow(i).getCell(j++).setText(column.getType());
            xwpfTable.getRow(i).getCell(j++).setText(column.isKey() ? "" : "");
            xwpfTable.getRow(i).getCell(j++).setText(column.isNullable() ? "?" : "");
            xwpfTable.getRow(i).getCell(j++).setText(column.getComment());
            xwpfTable.getRow(i).getCell(j++).setText(column.getExtra());
        }

    }

    File file = new File(generatedPath);
    if (!file.exists()) {
        file.mkdirs();
    }

    FileOutputStream fos = new FileOutputStream(generatedPath + "database.docx");
    xwpfDocument.write(fos);
    fos.close();

}

From source file:demo.poi.image.SimpleImages.java

License:Apache License

static void writeImageToDoc(String[] args) throws InvalidFormatException, IOException, FileNotFoundException {
    XWPFDocument doc = new XWPFDocument();
    XWPFParagraph p = doc.createParagraph();

    XWPFRun r = p.createRun();/* w w  w.jav a2 s.c  o m*/

    for (String imgFile : args) {
        int format;

        if (imgFile.endsWith(".emf"))
            format = XWPFDocument.PICTURE_TYPE_EMF;
        else if (imgFile.endsWith(".wmf"))
            format = XWPFDocument.PICTURE_TYPE_WMF;
        else if (imgFile.endsWith(".pict"))
            format = XWPFDocument.PICTURE_TYPE_PICT;
        else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg"))
            format = XWPFDocument.PICTURE_TYPE_JPEG;
        else if (imgFile.endsWith(".png"))
            format = XWPFDocument.PICTURE_TYPE_PNG;
        else if (imgFile.endsWith(".dib"))
            format = XWPFDocument.PICTURE_TYPE_DIB;
        else if (imgFile.endsWith(".gif"))
            format = XWPFDocument.PICTURE_TYPE_GIF;
        else if (imgFile.endsWith(".tiff"))
            format = XWPFDocument.PICTURE_TYPE_TIFF;
        else if (imgFile.endsWith(".eps"))
            format = XWPFDocument.PICTURE_TYPE_EPS;
        else if (imgFile.endsWith(".bmp"))
            format = XWPFDocument.PICTURE_TYPE_BMP;
        else if (imgFile.endsWith(".wpg"))
            format = XWPFDocument.PICTURE_TYPE_WPG;
        else {
            System.err.println("Unsupported picture: " + imgFile
                    + ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
            continue;
        }

        r.setText(imgFile);
        r.addBreak();
        r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200
        // pixels
        r.addBreak(BreakType.PAGE);
    }

    FileOutputStream out = new FileOutputStream("images.docx");
    doc.write(out);
    out.close();
    // doc.close();
}

From source file:easyoffice.word.WordMaker.java

private static void saveDoc(XWPFDocument doc) {

    if (!OUTPUT_PPT_NAME.contains(".docx")) {
        OUTPUT_PPT_NAME += ".docx";
    }//from  w  ww .  j a  v a2 s  .  c  om

    try {
        File file = new File(OUTPUT_PPT_NAME);
        FileOutputStream out = new FileOutputStream(file);
        doc.write(out);
        out.close();
        System.out.println("Documento guardado");
    } catch (IOException ex) {
        System.err.println("El documento no puede ser guardado");
        System.err.println(ex.getMessage());
    }
}

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);/* w w  w .  j ava  2  s  .com*/
            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 . ja v  a 2s. 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);//from  w  ww .j a  v a2s.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:edu.gatech.pmase.capstone.awesome.impl.output.DisasterResponseTradeStudyOutputer.java

License:Open Source License

@Override
public Path createOutputFile(final List<DRTSArchitectureResult> results,
        final List<DisasterEffect> selectedDisasterEffects, final List<TerrainEffect> selectedTerrainEffects)
        throws IOException, InvalidFormatException {
    // set time/*from   w  ww .ja  v a 2  s.  co  m*/
    now = ZonedDateTime.now();

    LOGGER.info("Creating results architecture file.");
    final String filename = "DRTS-Results-" + fileNameFormatter.format(now) + ".docx";

    // create paths
    final Path templatePath = Paths.get(
            DisasterResponseTradeStudyPropertiesSingleton.getInstance().getResultsDirectory(),
            DisasterResponseTradeStudyPropertiesSingleton.getInstance().getResultsTemplate());

    final Path resultsDir = Paths
            .get(DisasterResponseTradeStudyPropertiesSingleton.getInstance().getResultsDirectory());

    Path resultPath = Paths
            .get(DisasterResponseTradeStudyPropertiesSingleton.getInstance().getResultsDirectory(), filename);

    // copy template file
    final File workbookFile = templatePath.toFile();

    if (workbookFile.exists() && !workbookFile.isDirectory() && workbookFile.canRead()) {
        LOGGER.debug("Using results template file: " + workbookFile.getAbsolutePath());
        final XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(workbookFile));

        // get table
        final List<XWPFTable> tables = xdoc.getTables();

        // set values
        DRTSArchitectureResult result = null;

        if (null != results && !results.isEmpty()) {
            result = results.get(0);

            // create platform weightings table
            this.createOptionWeightingTable(result.getPlatform(), tables.get(PLATFORM_WEIGHTING_TABLE_INDEX));

            // create comm weighting table
            this.createOptionWeightingTable(result.getComms(), tables.get(COMM_WEIGHTING_TABLE_INDEX));

            // create sensor weighting table
            this.createOptionWeightingTable(result.getSensor(), tables.get(SENSOR_WEIGHTING_TABLE_INDEX));
        } else {
            LOGGER.warn("No architecture result found, cannot place into output result.");
        }

        // create arch table
        this.createArchTable(result, tables.get(ARCH_RESULT_TABLE_INDEX));

        // create disaster effect table
        this.createSelectedDisasterTable(selectedDisasterEffects, tables.get(SELECTED_DISASTER_TABLE_INDEX));

        // create selected terrain table
        this.createSelectedTerrainTable(selectedTerrainEffects, tables.get(SELECTED_TERRAIN_TABLE_INDEX));

        // create details
        this.createReportDetails(xdoc);

        // get result file
        final File resultFile = resultPath.toFile();
        LOGGER.debug("Trying to use result file: " + resultFile.getAbsolutePath());
        LOGGER.debug("Result file is in result directory: " + resultsDir.toAbsolutePath());

        if (!resultFile.isDirectory() && Files.isDirectory(resultsDir) && Files.isWritable(resultsDir)) {
            LOGGER.debug("Creating result file: " + resultFile.getAbsolutePath());
            // write out result
            try (final FileOutputStream outStream = new FileOutputStream(resultFile)) {
                xdoc.write(outStream);
            }
        } else {
            LOGGER.error("Cannot create output result file at path: " + resultFile.getAbsolutePath());
            resultPath = null;
        }
    } else {
        LOGGER.error("Cannot read input workbook file at path: " + templatePath.toString());
        resultPath = null;
    }

    return resultPath;
}