ScreenshotNeo

BlogHow-to

How to Convert an HTML String to JPG with IronPDF

Render an in-memory HTML string with IronPDF, then export PDF pages to JPG with control over assets, DPI, dimensions, and page selection.

By the ScreenshotNeo team1 October 20267 min read

IronPDF converts an HTML string to JPG in two documented steps: render the string to an in-memory PdfDocument with ChromePdfRenderer.RenderHtmlAsPdf, then rasterize that PDF with PdfDocument.ToJpegImages. The result is one JPG per selected PDF page. There is no documented single RenderHtmlAsJpg method.

1. Install IronPDF

IronPDF supports .NET Framework 4.6.2+, .NET Core 3.1+, and .NET 5+ according to its quickstart. On Windows, install the Visual C++ Redistributable required by the renderer. Add the NuGet package:

dotnet add package IronPdf

See the IronPDF quickstart for supported runtimes and platform prerequisites.

2. Convert an HTML string to JPG

This complete C# example renders an HTML string, then writes JPG files using an asterisk in the filename pattern. IronPDF replaces the asterisk with the zero-based page number.

using IronPdf;

string html = """
<!doctype html>
<html>
  <head>
    <meta charset=\"utf-8\">
    <style>
      body { font-family: Arial, sans-serif; margin: 40px; }
      h1 { color: #1f2937; }
    </style>
  </head>
  <body>
    <h1>Hello IronPDF</h1>
    <p>This HTML string is rendered to JPG.</p>
  </body>
</html>
""";

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);

Directory.CreateDirectory("output");
pdf.ToJpegImages("output/shot_*.jpg", DPI: 150);

The HTML is rendered in memory. A one-page document creates shot_0.jpg; a multi-page document creates one file for each page.

IronPDF documents RenderHtmlAsPdf as supporting HTML5, CSS3, JavaScript, and images. ChromePdfRenderer API reference

3. Resolve CSS, images, scripts, and fonts

Relative URLs need a base path. Pass a local directory as the second argument to RenderHtmlAsPdf. The directory should contain the referenced files, or use absolute and remote URLs in the HTML.

using IronPdf;

string html = """
<html>
  <head>
    <link rel=\"stylesheet\" href=\"css/site.css\">
  </head>
  <body>
    <img src=\"images/logo.png\" alt=\"Logo\">
    <h1 class=\"title\">Invoice</h1>
  </body>
</html>
""";

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html, "/var/www/invoice-assets");
pdf.ToJpegImages("invoice_*.jpg", DPI: 150);

On Windows, use a verbatim path such as C:\\site\\assets\\ . Keep the base directory stable and make sure the process account can read every file.

4. Control JPG resolution and dimensions

ToJpegImages defaults to 96 DPI. Choose a DPI that matches the use case: lower values reduce output size, while higher values create more pixels and larger files. The API also provides overloads for nullable maximum width and height in pixels.

// Higher-resolution export
pdf.ToJpegImages("output/high_*.jpg", DPI: 300);

// Constrain the rasterized page to a maximum width and height.
// Use the overload exposed by your installed IronPDF version.
pdf.ToJpegImages("output/limited_*.jpg", MaximumWidth: 1600, MaximumHeight: 2200, DPI: 150);

Maximum dimensions are limits, not guaranteed exact output sizes. The final pixel dimensions depend on the PDF page size, content, DPI, and the selected limits.

5. Export selected pages

Page indexes are zero based. Use the page-selection overload when a multi-page render contains pages you do not need.

using System.Linq;

// Export only pages 0 and 2.
pdf.ToJpegImages(
    "output/selected_*.jpg",
    PageIndexes: new[] { 0, 2 },
    DPI: 150);

Check the overload names in the PdfDocument API reference for the IronPDF package version in your project. If a requested index does not exist, select valid indexes after inspecting the rendered document’s page count.

6. Flatten form fields before rasterizing

If your HTML produces a PDF with form-field values that must be included in the image, use the documented Flatten option on the JPEG export overload.

pdf.ToJpegImages(
    "output/form_*.jpg",
    DPI: 150,
    Flatten: true);

7. A reusable conversion method

This helper accepts an HTML string, an optional asset directory, an output pattern, and rendering settings.

using IronPdf;

public static class HtmlJpegConverter
{
    public static void Convert(
        string html,
        string outputPattern,
        string? basePath = null,
        int dpi = 150,
        int? maximumWidth = null,
        int? maximumHeight = null)
    {
        if (string.IsNullOrWhiteSpace(html))
            throw new ArgumentException("HTML cannot be empty.", nameof(html));

        if (string.IsNullOrWhiteSpace(outputPattern) || !outputPattern.Contains('*'))
            throw new ArgumentException("Output pattern must contain '*'.", nameof(outputPattern));

        var renderer = new ChromePdfRenderer();
        var pdf = basePath is null
            ? renderer.RenderHtmlAsPdf(html)
            : renderer.RenderHtmlAsPdf(html, basePath);

        pdf.ToJpegImages(
            outputPattern,
            MaximumWidth: maximumWidth,
            MaximumHeight: maximumHeight,
            DPI: dpi);
    }
}

HtmlJpegConverter.Convert(
    html: "<h1>Report</h1>",
    outputPattern: "output/report_*.jpg",
    dpi: 200,
    maximumWidth: 2000);

8. Pagination and layout behavior

IronPDF first lays out the HTML as a PDF. CSS, content length, page dimensions, images, fonts, and scripts therefore affect pagination. A document that looks like one screen in a browser can produce several PDF pages and several JPG files. Design page breaks deliberately, keep critical content away from page boundaries, and inspect every generated page when the output is used in a report or archive.

9. Troubleshooting

Symptom Cause Fix
CSS, images, or fonts are missing Relative URLs have no base path, or the process cannot read the files. Pass the asset directory as BaseUrlOrPath, verify paths and permissions, or use absolute URLs.
No output file appears The output pattern lacks *, or its directory does not exist. Use a pattern such as output_*.jpg and create the directory first.
Only the first page is expected but several JPGs appear The HTML paginated into multiple PDF pages. Shorten or reflow the HTML, adjust layout, or export only required zero-based page indexes.
Output is blurry The default 96 DPI is too low for the target size. Increase DPI and, if needed, remove restrictive maximum dimensions.
Output is unexpectedly large High DPI or large page dimensions create many pixels. Lower DPI, set maximum width or height, and avoid oversized page content.
Fonts differ from the source page The renderer cannot load the requested font. Provide local font files under the base path or use a reachable absolute font URL.
JavaScript-dependent content is absent The script failed, depended on unavailable resources, or had not completed during rendering. Make scripts self-contained where possible, verify referenced assets, and simplify asynchronous page initialization.
Windows native dependency error The required Visual C++ Redistributable is missing. Install the redistributable listed by the IronPDF quickstart for the target machine.
Selected page export fails A page index is outside the rendered document’s zero-based range. Use valid indexes from 0 through the last page index.

10. Performance, reliability, and cost considerations

  • Rendering cost: HTML is rendered first and then rasterized. Higher DPI, large pages, many images, and multi-page documents increase CPU, memory, and output size.
  • Memory: Keep the PdfDocument in scope only as long as needed. For batches, process a bounded number of documents at a time and write outputs promptly.
  • Repeatability: Bundle CSS, fonts, and images when deterministic output matters. Remote assets can change or become unavailable.
  • Pagination: Treat page count as data-dependent. Do not hard-code a single output filename unless your HTML is guaranteed to remain one page.
  • Deployment: Validate the .NET runtime, native dependencies, filesystem permissions, and font availability in the deployment environment before processing production jobs.
  • Licensing: Review the current IronPDF license terms for your application and deployment model before shipping.

11. Or skip the browser setup

If you only need a clean screenshot or JPG of a URL, ScreenshotNeo provides a single request instead of maintaining a rendering environment. It removes cookie and consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status.

See the ScreenshotNeo API documentation for the available options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', data));

ScreenshotNeo also supports PNG, JPEG, and PDF output, full-page capture with lazy images, element capture, custom CSS and JavaScript, device and viewport settings, waits, request blocking, headers and cookies, caching, signed links, asynchronous jobs, bulk capture, usage reporting, and an MCP server for AI agents. Every plan includes every feature. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots.

Create a free ScreenshotNeo account and start with 1,000 screenshots a month at no charge.

12. FAQ

Can IronPDF convert directly from an HTML string without creating an intermediate PDF file?

Yes. RenderHtmlAsPdf returns an in-memory PdfDocument; call ToJpegImages on that object without saving a PDF first.

What does the asterisk in the output filename mean?

It is a required page-number placeholder. For example, page_*.jpg becomes page_0.jpg, page_1.jpg, and so on.

Are page indexes one based?

No. The documented page-selection APIs use zero-based indexes.

What DPI should I choose?

Use 96 DPI when screen-sized output is sufficient. Increase it for print or detailed images, then check file size and memory usage.

Can I preserve relative URLs in the HTML?

Yes. Supply the directory containing the relative CSS, images, scripts, and fonts as the renderer’s base path.