When your output is an image (PNG/JPEG/WebP) instead of a PDF or page view, a few targeted CSS patterns make a big difference: scale images safely, keep tables tidy, and set typography that remains readable after rasterization. With Aspose.HTML for .NET, you control both the CSS and the rendering pipeline via ImageSaveOptions for reliable results.

Key Takeaways

  • Prefer responsive CSS: img{max-width:100%;height:auto} and table{table-layout:fixed} with explicit widths.
  • Use ImageSaveOptions to set DPI, page size/margins, media type (Screen vs Print), and output format.
  • For dense tables, apply border-collapse, padding, and word wrapping to avoid clipping.
  • Keep fonts consistent and test at the final DPI you plan to export.

Step-by-Step Guide

1) Load the HTML document

Load from a file for production, or compose from a string for quick tests. Provide a base URI so relative assets (CSS/images) resolve.

// Load an HTML file
using var document = new Aspose.Html.HTMLDocument("./sample.html");

// Or create from a string with a base URI
string html = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Styled Render</title>" +
              "<style>/* minimal defaults for image rendering */" +
              "html,body{margin:0;padding:0;font-family:Arial,Helvetica,sans-serif;color:#222}" +
              "img{max-width:100%;height:auto;display:block}" +
              "table{width:100%;border-collapse:collapse;table-layout:fixed}" +
              "th,td{border:1px solid #ddd;padding:6px 8px;vertical-align:top;word-wrap:break-word}" +
              "caption{caption-side:top;font-weight:bold;margin:6px 0}" +
              "@media print{body{font-size:12pt}}" +
              "</style></head><body>" +
              "<h1>Invoice</h1>" +
              "<img src=\"./assets/logo.png\" alt=\"Company logo\" style=\"width:240px\">" +
              "<table><caption>Items</caption><tr><th>Item</th><th>Qty</th><th>Price</th></tr>" +
              "<tr><td>Widget A very long text that will wrap</td><td>5</td><td>$12.00</td></tr>" +
              "<tr><td>Widget B</td><td>2</td><td>$9.50</td></tr></table>" +
              "</body></html>";
using var inlineDoc = new Aspose.Html.HTMLDocument(html, ".");

2) Configure rendering for images

Set DPI, page geometry, CSS media, and target image format via ImageSaveOptions.

var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Png)
{
    UseAntialiasing = true
};
options.HorizontalResolution = 300; // print-quality DPI
options.VerticalResolution   = 300;
options.Css.MediaType        = Aspose.Html.Rendering.MediaType.Screen; // or Print

// Page setup — render as A4 with 10 mm margins
var mm = Aspose.Html.Drawing.Length.FromMillimeters;
options.PageSetup.AnyPage = new Aspose.Html.Drawing.Page(
    new Aspose.Html.Drawing.Size(mm(210), mm(297)),
    new Aspose.Html.Drawing.Margin(mm(10), mm(10), mm(10), mm(10))
);

3) Render to an image file

Aspose.Html.Converters.Converter.ConvertHTML(inlineDoc, options, "out/styled.png");

Complete Example (Compilable C#)

using System;
using System.IO;
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
using Aspose.Html.Rendering;        // MediaType
using Aspose.Html.Rendering.Image;  // ImageFormat
using Aspose.Html.Drawing;          // Length, Size, Margin, Page

namespace AsposeHtmlStylingForImages
{
    internal static class Program
    {
        // How to run:
        // 1) dotnet new console -n AsposeHtmlStylingForImages
        // 2) cd AsposeHtmlStylingForImages
        // 3) dotnet add package Aspose.HTML
        // 4) Replace Program.cs with this file's contents
        // 5) dotnet run -- "path-to-input.html"   (argument optional)
        private static void Main(string[] args)
        {
            string outDir = Path.Combine(Directory.GetCurrentDirectory(), "out");
            Directory.CreateDirectory(outDir);

            HTMLDocument document;
            if (args.Length > 0 && File.Exists(args[0]))
            {
                document = new HTMLDocument(args[0]);
            }
            else
            {
                // Inline demo HTML with sensible defaults for image rendering
                string html = "<!DOCTYPE html>" +
                              "<html><head><meta charset=\\\"utf-8\\\"><title>Styled Image Render</title>" +
                              "<style>html,body{margin:0;padding:0;font-family:Arial,Helvetica,sans-serif;color:#222}" +
                              "img{max-width:100%;height:auto;display:block}" +
                              "table{width:100%;border-collapse:collapse;table-layout:fixed}" +
                              "th,td{border:1px solid #ddd;padding:6px 8px;vertical-align:top;word-wrap:break-word}" +
                              "caption{caption-side:top;font-weight:bold;margin:6px 0}" +
                              "h1{margin:12px 0}" +
                              "@media print{body{font-size:12pt}}" +
                              "</style></head><body>" +
                              "<h1>Styled Render</h1>" +
                              "<img src=\\\"./assets/photo.jpg\\\" alt=\\\"Sample photo\\\" style=\\\"width:320px\\\">" +
                              "<table><caption>Summary</caption><tr><th>Column A</th><th>Column B</th></tr>" +
                              "<tr><td>Long cell content that wraps nicely in fixed layout tables.</td><td>42</td></tr></table>" +
                              "</body></html>";
                document = new HTMLDocument(html, ".");
            }

            using (document)
            {
                // PNG at 300 DPI (screen CSS)
                var png = new ImageSaveOptions(ImageFormat.Png) { UseAntialiasing = true };
                png.HorizontalResolution = 300; png.VerticalResolution = 300; png.Css.MediaType = MediaType.Screen;
                var mm = Length.FromMillimeters;
                png.PageSetup.AnyPage = new Page(new Size(mm(210), mm(297)), new Margin(mm(10), mm(10), mm(10), mm(10)));
                string pngPath = Path.Combine(outDir, "styled.png");
                Converter.ConvertHTML(document, png, pngPath);
                Console.WriteLine($"Saved: {pngPath}");

                // JPEG at 150 DPI (print CSS)
                var jpg = new ImageSaveOptions(ImageFormat.Jpeg);
                jpg.HorizontalResolution = 150; jpg.VerticalResolution = 150; jpg.Css.MediaType = MediaType.Print;
                jpg.PageSetup.AnyPage = png.PageSetup.AnyPage; // reuse geometry
                string jpgPath = Path.Combine(outDir, "styled.jpg");
                Converter.ConvertHTML(document, jpg, jpgPath);
                Console.WriteLine($"Saved: {jpgPath}");
            }
        }
    }
}

How to run

  1. dotnet new console -n AsposeHtmlStylingForImages
  2. cd AsposeHtmlStylingForImages
  3. dotnet add package Aspose.HTML
  4. Replace Program.cs with the code above
  5. dotnet run -- "path-to-input.html"

Styling tips for crisp images

  • Images: always set max-width:100% and height:auto. Use high‑resolution sources for print DPI.
  • Tables: fixed layout, collapsed borders, and padding prevent overflow and keep grid lines sharp.
  • Text: test sizes at the target DPI; prefer common sans‑serif stacks for predictable metrics.
  • Media rules: switch between Screen and Print CSS to match your destination.

FAQ

Q1. How do I apply custom CSS without editing the HTML file? Embed a <style> block via string composition (as above) or host a CSS file and reference it with a <link> tag; ensure the document’s base URI points to the folder that contains it.

Q2. What DPI should I use? 96–150 for screens; 300 for print. Higher DPI increases file size and render time.

Q3. Can I export to WebP or TIFF? Yes. Use new ImageSaveOptions(ImageFormat.Webp) or ImageFormat.Tiff depending on your delivery needs.

Q4. Why do my table borders look fuzzy? Ensure border-collapse:collapse, avoid fractional CSS pixels, and render at a DPI that matches your target use.

Q5. How do I avoid missing fonts? Package web‑safe fonts or embed via @font-face URLs that are accessible to the renderer; verify glyph coverage.

Conclusion

By combining clean, responsive CSS with ImageSaveOptions (DPI, media, page geometry), you can generate sharp, predictable HTML → image renders for dashboards, invoices, and reports. Test at your target DPI and refine table and text rules until they read well at the final bitmap size.

More in this category