Save output to a stream

By default, GroupDocs.Viewer saves output results to the local disk. Also, it can provide results as a stream.

To provide output results as a stream, use one of the following interfaces:

  • FileStreamFactory defines methods to instantiate and release the output file streams.
  • PageStreamFactory defines methods to instantiate and release the output page streams.
  • ResourceStreamFactory defines the methods to create resource URLs, instantiate, and release output HTML resource streams.

Use these interface as follows:

The following code snippet shows how to render to HTML with embedded resources and to provide the output result as a stream. To do this, it implements the PageStreamFactory interface only.

import com.groupdocs.viewer.Viewer;
import com.groupdocs.viewer.interfaces.PageStreamFactory;
import com.groupdocs.viewer.options.HtmlViewOptions;
import com.groupdocs.viewer.options.ViewOptions;
// ...

final List<ByteArrayOutputStream> pages = new ArrayList<>();

try (Viewer viewer = new Viewer("sample.docx")) {

    PageStreamFactory pageStreamFactory = new PageStreamFactory() {

        @Override
        public OutputStream createPageStream(int pageNumber) {
            ByteArrayOutputStream pageStream = new ByteArrayOutputStream();

            pages.add(pageStream);

            return pageStream;
        }

        @Override
        public void closePageStream(int pageNumber, OutputStream outputStream) {
            //Do not release page stream as we'll need to keep the stream open
        }
    };

    ViewOptions viewOptions = HtmlViewOptions.forEmbeddedResources(pageStreamFactory);

    viewer.view(viewOptions);
}