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:
1class MemoryStreamProvider : ICreateStreamProvider
2{
3 // List of MemoryStream objects created during the document rendering
4 public List<MemoryStream> Streams { get; } = new List<MemoryStream>();
5
6 public Stream GetStream(string name, string extension)
7 {
8 // This method is called when only one output stream is required, for instance for XPS, PDF or TIFF formats
9 MemoryStream result = new MemoryStream();
10 Streams.Add(result);
11 return result;
12 }
13
14 public Stream GetStream(string name, string extension, int page)
15 {
16 // 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.)
17 MemoryStream result = new MemoryStream();
18 Streams.Add(result);
19 return result;
20 }
21
22 public void ReleaseStream(Stream stream)
23 {
24 // Here you can release the stream filled with data and, for instance, flush it to the hard-drive
25 }
26
27 public void Dispose()
28 {
29 // Releasing resources
30 foreach (var stream in Streams)
31 stream.Dispose();
32 }
33}
Let’s look at the main parts of the MemoryStreamProvider
class:
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.- Implementation of the
GetStream()
methods. GetStream() methods create new MemoryStream objects, add them to the Streams list, and return them as output streams. - 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. - Implementation of the
Dispose()
method. This method is called to release any resources held by theMemoryStreamProvider
class. This implementation disposes of all the MemoryStream objects in the Streams list using aforeach
loop.
C# MemoryStream to File
The following C# code demonstrates how to use the MemoryStreamProvider
class and the Aspose.HTML for .NET 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:
- Create a new instance of the
MemoryStreamProvider
class. It will be used as an output stream for the conversion process. - Initialize an HTML document using the HTMLDocument class.
- Use the
ImageSaveOptions() constructor to configure the image save options, such as the
ImageFormat
– JPEG (in this case). - Call the ConvertHTML(document, options, provider) method to convert the HTMLDocument object to an image using save options and MemoryStreamProvider.
- Use the
foreach
loop to iterate over eachMemoryStream
object in theStreams
property of thestreamProvider
object. Each MemoryStream represents a page of the converted HTML document. - 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. - Use the
File.Create()
method inside the loop to create an output file for the current page. - Use the
memory.CopyTo()
method to copy the contents of the memory stream to the FileStream object, which represents the output file. - After processing each page, the page counter is incremented to keep track of the page number for the output file names.
1// Create an instance of MemoryStreamProvider
2using (var streamProvider = new MemoryStreamProvider())
3{
4 // Prepare HTML code
5 var code = @"<style>
6 div { page-break-after: always; }
7 </style>
8 <div style='border: 1px solid red; width: 300px'>First Page</div>
9 <div style='border: 1px solid red; width: 300px'>Second Page</div>
10 <div style='border: 1px solid red; width: 300px'>Third Page</div>
11 ";
12 // Initialize an HTML document from the HTML code
13 using var document = new HTMLDocument(code, ".");
14 {
15 // Convert HTML to Image by using the MemoryStreamProvider
16 Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
17
18 // Get access to the memory stream that contains the result data
19 var page = 1;
20 foreach (var memory in streamProvider.Streams)
21 {
22 memory.Seek(0, SeekOrigin.Begin);
23
24 // Flush the result data to the output file
25 using (FileStream fs = File.Create(Path.Combine(OutputDir, "page_" + page + ".jpg")))
26 {
27 memory.CopyTo(fs);
28 }
29 page++;
30 }
31 }
32}
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!