Convert HTML from ZIP Archive to JPG in C#

To convert HTML from a ZIP archive to JPG in C#, create a custom MessageHandler that resolves zip resources, add it to INetworkService.MessageHandlers, open the packaged HTML document, and render it to a raster image.

When an HTML or XHTML document references images, stylesheets, scripts, or fonts, keeping the document and resources in one ZIP archive makes the input package portable. Aspose.HTML for .NET can process that package through a custom message handler and render the final document to JPG.

Create a Custom Message Handler

Aspose.HTML for .NET supports custom message handlers for controlling resource loading. In this article, the handler reads ZIP archive entries when the document requests resources through the zip protocol.

Take the following steps:

  1. Use the Aspose.Html.Net namespace, which contains networking classes and interfaces.
  2. Define a ZipArchiveMessageHandler class derived from MessageHandler.
  3. Configure the handler so it processes only ZIP-based resource requests.
1using Aspose.Html.Net;
2...
3
4	class ZipArchiveMessageHandler : MessageHandler
5	{
6	}

After the class is declared:

  1. Initialize an instance of the ZipArchiveMessageHandler class and define a Filter property for it.
  2. Override the Invoke() method of the MessageHandler class to implement the custom message handler behavior.
 1// Implement ZipArchiveMessageHandler in C#
 2
 3// This message handler prints a message about start and finish processing request
 4class ZipArchiveMessageHandler : MessageHandler, IDisposable
 5{
 6    private string filePath;
 7    private Archive archive;
 8
 9    // Initialize an instance of the ZipArchiveMessageHandler class
10    public ZipArchiveMessageHandler(string path)
11    {
12        this.filePath = path;
13        Filters.Add(new ProtocolMessageFilter("zip"));
14    }
15
16    // Override the Invoke() method
17    public override void Invoke(INetworkOperationContext context)
18    {
19        // Call the GetFile() method that defines the logic in the Invoke() method
20        byte[] buff = GetFile(context.Request.RequestUri.Pathname.TrimStart('/'));
21        if (buff != null)
22        {
23            // Checking: if a resource is found in the archive, then return it as a Response
24            context.Response = new ResponseMessage(HttpStatusCode.OK)
25            {
26                Content = new ByteArrayContent(buff)
27            };
28            context.Response.Headers.ContentType.MediaType = MimeType.FromFileExtension(context.Request.RequestUri.Pathname);
29        }
30        else
31        {
32            context.Response = new ResponseMessage(HttpStatusCode.NotFound);
33        }
34
35        // Call the next message handler
36        Next(context);
37    }
38
39
40    byte[] GetFile(string path)
41    {
42        path = path.Replace(@"\", @"/");
43        ArchiveEntry result = GetArchive().Entries.FirstOrDefault(x => path == x.Name);
44        if (result != null)
45        {
46            using (Stream fs = result.Open())
47            using (MemoryStream ms = new MemoryStream())
48            {
49                fs.CopyTo(ms);
50                return ms.ToArray();
51            }
52        }
53        return null;
54    }
55
56    Archive GetArchive()
57    {
58        return archive ??= new Archive(filePath);
59    }
60
61    public void Dispose()
62    {
63        archive?.Dispose();
64    }
65}

The handler implementation includes these parts:

Add ZipArchiveMessageHandler to the Pipeline

Message handlers work as a chain. After the handler is created, add ZipArchiveMessageHandler to the pipeline used by the document configuration. The Configuration constructor creates a configuration object; then GetService<INetworkService>() and MessageHandlers.Add() are used to append the zip handler.

To convert HTML from a ZIP archive to JPG:

  1. Create a Configuration object.
  2. Add the ZipArchiveMessageHandler instance to INetworkService.MessageHandlers.
  3. Open the HTML document from the ZIP archive with HTMLDocument(address, configuration).
  4. Configure image output for JPG rendering.
  5. Render the document to a .jpg file.
 1// Convert HTML from a ZIP archive to JPG using C#
 2
 3// Add this line before you try to use the 'IBM437' encoding
 4System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
 5
 6// Prepare path to a source zip file
 7string documentPath = Path.Combine(DataDir, "test.zip");
 8
 9// Prepare path for converted file saving
10string savePath = Path.Combine(OutputDir, "zip-to-jpg.jpg");
11
12// Create an instance of ZipArchiveMessageHandler
13using ZipArchiveMessageHandler zip = new ZipArchiveMessageHandler(documentPath);
14
15// Create an instance of the Configuration class
16using Configuration configuration = new Configuration();
17
18// Add ZipArchiveMessageHandler to the chain of existing message handlers
19configuration
20    .GetService<INetworkService>()
21    .MessageHandlers.Add(zip);
22
23// Initialize an HTML document with specified configuration
24using HTMLDocument document = new HTMLDocument("zip:///test.html", configuration);
25
26// Create an instance of Rendering Options
27ImageRenderingOptions options = new ImageRenderingOptions()
28{
29    Format = ImageFormat.Jpeg
30};
31
32// Create an instance of Image Device
33using ImageDevice device = new ImageDevice(options, savePath);
34
35// Render ZIP to JPG
36document.RenderTo(device);

In the example, the ZIP archive (test.zip) has the HTML document (test.html) in which all related resources have paths relative to the HTML document.

Note: The HTMLDocument(address, configuration) constructor takes the absolute path to the ZIP archive. Related resources can still use paths relative to the HTML document inside the archive, as shown in the example.

For more information about rendering settings, see Fine-Tuning Converters and the RenderTo(device) method.

You can download the complete C# examples and data files from GitHub.

FAQ

Why convert HTML from a ZIP archive to JPG?

Use this workflow when the HTML document and its resources must stay packaged together, but the final result should be a raster image.

Can the ZIP archive contain CSS and images?

Yes. The archive can contain the HTML document and related resources such as CSS files, images, scripts, and fonts referenced by relative paths.

Is the ZIP handler specific to JPG output?

No. The handler resolves resources from the archive. The output format is controlled by the rendering workflow, so the same idea can be used for PDF or other supported outputs.

Related Articles