How to get an output stream when viewing a document

By default GroupDocs.Viewer saves output results to the local disk, but we also provide a way to save output results into a stream. 

There are three interfaces that we can utilize:

  • FileStreamFactory - defines the methods that are required for instantiating and releasing output file stream.
  • PageStreamFactory - defines the methods that are required for instantiating and releasing output page stream.
  • ResourceStreamFactory - defines the methods that are required for creating resource URL, instantiating and releasing output HTML resource stream.

Let’s say that instead of saving rendering results to the local disk we want to have all the output file or output files in form of stream or list of streams.

What we need to do is to implement one or two of the interfaces listed above. 

In this example, we’ll render into HTML with embedded resources so we need to implement only PageStreamFactory interface.

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

        Viewer viewer = new Viewer("sample.docx");

        MemoryPageStreamFactory pageStreamFactory = new MemoryPageStreamFactory(pages);

        ViewOptions viewOptions = HtmlViewOptions.forEmbeddedResources(pageStreamFactory);

        viewer.view(viewOptions);
    class MemoryPageStreamFactory implements PageStreamFactory {
        private final List<ByteArrayOutputStream> _pages;

        public MemoryPageStreamFactory(List<ByteArrayOutputStream> pages) {
            _pages = pages;
        }

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

            _pages.add(pageStream);

            return pageStream;
        }

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

More resources

GitHub Examples

You may easily run the code above and see the feature in action in our GitHub examples:

Free Online App

Along with full-featured Java library we provide simple but powerful free Apps. You are welcome to view Word, PDF, Excel, PowerPoint documents with free to use online GroupDocs Viewer App.