Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
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.
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:
ZipArchiveMessageHandler class derived from
MessageHandler.1using Aspose.Html.Net;
2...
3
4 class ZipArchiveMessageHandler : MessageHandler
5 {
6 }After the class is declared:
ZipArchiveMessageHandler class and define a Filter property for it.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:
ZipArchiveMessageHandler inherits from the base MessageHandler class and stores the archive and the string representation of the path to the archive. Inheriting from IDisposable provides a mechanism for deterministic release of unmanaged resources.
The handler uses a protocol filter, so it works only with the "zip" protocol.
Filtering messages by resource protocol is implemented using the
ProtocolMessageFilter class. The ProtocolMessageFilter() constructor initializes a new instance of the ProtocolMessageFilter class. It takes the "zip" protocols as a parameter.
The
Invoke() method implements the message handler behavior. It is called for each handler in the pipeline and takes context as a parameter. The GetFile() method defines the resource lookup logic and then the handler can call Next(context).
The GetFile() method searches for data as a byte array in the ZIP archive based on Request and then forms Response.
context provides contextual information for network services. In Aspose.HTML, it is represented by the
INetworkOperationContext interface, which exposes
Request and
Response properties.
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:
Configuration object.ZipArchiveMessageHandler instance to INetworkService.MessageHandlers..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.
Use this workflow when the HTML document and its resources must stay packaged together, but the final result should be a raster image.
Yes. The archive can contain the HTML document and related resources such as CSS files, images, scripts, and fonts referenced by relative paths.
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.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.