Output Streams – C# MemoryStream

Output Streams – C#

In conversion operations, we normally save the rendering result to the file. However, in some cases, you may need to store the result in memory or send it to remote storage. You can easily do this by implementing the specialized ICreateStreamProvider interface and using it as an input parameter to the converter. This interface represents a callback that uses when a new output stream is required.

Note: It may be invoked a few times when multiple output streams are required. The scenario when this case is possible is rendering HTML to the set of image files.

MemoryStreamProvider class

Aspose.HTML C# library allows realizing the MemoryStreamProvider class as a custom implementation of the ICreateStreamProvider interface. The MemoryStreamProvider class provides C# MemoryStream objects as output streams for writing data, which can be stored in memory as a stream.

Using a C# MemoryStream helps to avoid latencies commonly associated with reading or writing files on a disk. Additionally, because the contents of a MemoryStream stay in memory, physical space on the disk is not utilized. The C# code below is an example of the application that uses ICreateStreamProvider to store the rendering result in memory and flush it to the file later:

 1using Aspose.Html.IO;
 2using System.Collections.Generic;
 3using System.IO;
 4...
 5    class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider
 6    {
 7        // List of MemoryStream objects created during the document rendering
 8        public List<MemoryStream> Streams { get; } = new List<MemoryStream>();
 9
10        public Stream GetStream(string name, string extension)
11        {
12            // This method is called when only one output stream is required, for instance for XPS, PDF or TIFF formats
13            MemoryStream result = new MemoryStream();
14            Streams.Add(result);
15            return result;
16        }
17
18        public Stream GetStream(string name, string extension, int page)
19        {
20            // This method is called when the creation of multiple output streams are required. For instance, during the rendering HTML to list of image files (JPG, PNG, etc.)
21            MemoryStream result = new MemoryStream();
22            Streams.Add(result);
23            return result;
24        }
25
26        public void ReleaseStream(Stream stream)
27        {
28            //  Here you can release the stream filled with data and, for instance, flush it to the hard-drive
29        }
30
31        public void Dispose()
32        {
33            // Releasing resources
34            foreach (var stream in Streams)
35                stream.Dispose();
36        }
37    }

Let’s look at the main parts of the MemoryStreamProvider class:

  1. Streams property. A list of MemoryStream objects is created during the document rendering. These objects will store the data that is written to the output streams.
  2. Implementation of the GetStream() methods. GetStream() methods create new MemoryStream objects, add them to the Streams list, and return them as output streams.
  3. Implementation of the ReleaseStream() method. The ReleaseStream() method releases a Stream object filled with data. In this implementation, the method is empty. Still, you can customize it to perform operations such as flushing the stream to a hard drive or releasing any resources associated with the stream.
  4. Implementation of the Dispose() method. This method is called to release any resources held by the MemoryStreamProvider class. This implementation disposes of all the MemoryStream objects in the Streams list using a foreach loop.

C# MemoryStream to File

The following C# code demonstrates how to use the MemoryStreamProvider class and the Aspose.HTML library to convert a multiple-page HTML document to JPG and save the image to a file. Let’s look at the example where the following steps are performed:

  1. Create a new instance of the MemoryStreamProvider class. It will be used as an output stream for the conversion process.
  2. Initialize an HTML document using the HTMLDocument class.
  3. Use the ImageSaveOptions() constructor to configure the image save options, such as the ImageFormat – JPEG (in this case).
  4. Call the ConvertHTML(document, options, provider) method to convert the HTMLDocument object to an image using save options and MemoryStreamProvider.
  5. Use the foreach loop to iterate over each MemoryStream object in the Streams property of the streamProvider object. Each MemoryStream represents a page of the converted HTML document.
  6. Call the memory.Seek() method on the memory stream to set the position to the beginning. This ensures that the entire content of the stream will be copied to the output file.
  7. Use the File.Create() method inside the loop to create an output file for the current page.
  8. Use the memory.CopyTo() method to copy the contents of the memory stream to the FileStream object, which represents the output file.
  9. After processing each page, the page counter is incremented to keep track of the page number for the output file names.
 1using Aspose.Html;
 2using System.IO;
 3using Aspose.Html.Converters;
 4using Aspose.Html.Rendering.Image;
 5using Aspose.Html.Saving;
 6...
 7    // Create an instance of MemoryStreamProvider
 8    using (var streamProvider = new MemoryStreamProvider())
 9    {
10        // Prepare HTML code
11        var code = @"<style>
12                    div { page-break-after: always; }
13                    </style>
14                    <div style='border: 1px solid red; width: 300px'>First Page</div>
15                    <div style='border: 1px solid red; width: 300px'>Second Page</div>
16                    <div style='border: 1px solid red; width: 300px'>Third Page</div>
17                  ";
18        // Initialize an HTML document from the HTML code
19        using var document = new HTMLDocument(code, ".");
20        {
21            // Convert HTML to Image by using the MemoryStreamProvider
22            Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
23
24            // Get access to the memory stream that contains the result data
25            var page = 1;
26            foreach (var memory in streamProvider.Streams)
27            {
28                memory.Seek(0, SeekOrigin.Begin);
29
30                // Flush the result data to the output file
31                using (FileStream fs = File.Create(Path.Combine(OutputDir, "output_" + page + ".jpg")))
32                {
33                    memory.CopyTo(fs);
34                }
35                page++;
36            }
37        }
38    }

Aspose.HTML offers free online Converters for converting HTML, XHTML, MHTML, EPUB, XML and Markdown files to a variety of popular formats. You can easily convert HTML to PDF, HTML to JPG, SVG to PDF, MHTML to PDF, or MD to HTML. Just select a file, choose the format to convert, and you’re done. It’s fast and completely free!

Text “Banner Free Online Converters”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.