2

is it possible to convert a XWPFDocument to byte[]? I don't want to save it into a file because I don't need it. if there is a possible way to do it, it would help

SH A
  • 95
  • 1
  • 9
  • 1
    [POIXMLDocument.write](https://poi.apache.org/apidocs/dev/org/apache/poi/ooxml/POIXMLDocument.html#write-java.io.OutputStream-) takes an `java.io.OutputStream` as parameter. That also can be a `ByteArrayOutputStream`. – Axel Richter Oct 24 '19 at 08:46
  • can you give more explanation? – SH A Oct 24 '19 at 10:05

1 Answers1

6

A XWPFDocument extends POIXMLDocument and it's write method takes an java.io.OutputStream as parameter. That also can be a ByteArrayOutputStream. So if the need is to get a XWPFDocument as an byte array, then write it into a ByteArrayOutputStream and then get the array from the method ByteArrayOutputStream.toByteArray.

Example:

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

public class CreateXWPFDocumentAsByteArray {

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

  XWPFDocument document = new XWPFDocument();
  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun(); 
  run.setBold(true);
  run.setFontSize(22);
  run.setText("The paragraph content ...");
  paragraph = document.createParagraph();

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  document.write(out);
  out.close();
  document.close();

  byte[] xwpfDocumentBytes = out.toByteArray();
  // do something with the byte array
  System.out.println(xwpfDocumentBytes);

  // to prove that the byte array really contains the XWPFDocument 
  try (FileOutputStream stream = new FileOutputStream("./XWPFDocument.docx")) {
    stream.write(xwpfDocumentBytes);
  } 

 }
}
Axel Richter
  • 56,077
  • 6
  • 60
  • 87