Spring Boot does not convert HTML into pixels by itself. It hosts the application; a rendering engine performs layout and produces an image. For controlled, well-formed templates, use OpenHTMLtoPDF and (when needed) Apache PDFBox to rasterize a PDF page. For JavaScript-heavy pages that must behave like a browser, evaluate JavaFX WebView or another browser-capable service. Your choice depends on CSS fidelity, script execution, page size, output format, and the server runtime.
Choose the rendering path first
Decide what “HTML” means in your application before selecting a library:
- Trusted templates you control: OpenHTMLtoPDF is a pure-Java option that renders a reasonable subset of well-formed XML/XHTML and some HTML5 using CSS 2.1 and later standards. It can output PDF or images, but it is not a browser.
- Paginated documents: render HTML to PDF, then use PDFBox to rasterize one or more pages. PDFBox exposes image format and DPI controls.
- Browser-like pages: JavaFX WebView can render local or remote HTML, and its WebEngine executes JavaScript. Validate packaging and headless operation on your target operating system and container.
OpenHTMLtoPDF explicitly warns that modern arbitrary HTML will not necessarily render well; it does not run JavaScript and does not implement many modern standards, including flex and grid. Therefore, a template designed for that supported subset is materially different from a website screenshot.
Define the image contract
Write down these requirements before coding:
- PNG for lossless text and transparency, or JPEG for smaller photographic output.
- Fixed viewport dimensions versus the complete document.
- One image versus one image per PDF page.
- Target width and height, background color, and raster DPI.
- Whether fonts, SVG, images, and other assets are local or loaded remotely.
- Whether JavaScript, cookies, authentication headers, or other browser behavior is required.
These decisions prevent a common mismatch: a PDF-oriented renderer may produce a correct paginated document while a request actually requires a browser viewport screenshot.
#1 Best Overall
OpenHTMLtoPDF plus PDFBox: a practical Spring Boot implementation
The following service renders an HTML string to PDF in memory and converts the first page to a PNG. It is suitable for templates that fit the renderer’s supported HTML and CSS subset. Use the current compatible releases of OpenHTMLtoPDF and PDFBox, and align them with the Java version supported by your Spring Boot application. Check the projects’ dependency and license information before deployment.
Maven dependencies
Add the OpenHTMLtoPDF PDFBox backend and Apache PDFBox to your build using versions selected from their current documentation. The PDFBox getting-started page currently documents the 3.0 line; do not copy a version blindly if your application uses a different compatibility baseline.
<!-- Select current versions compatible with your Java and Spring Boot baseline -->
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>CURRENT_COMPATIBLE_VERSION</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>CURRENT_COMPATIBLE_VERSION</version>
</dependency>
Replace the version markers with released versions you have verified. Keeping the versions explicit in your own build is important for reproducibility; the project pages are the authority for current releases.
Rendering service
package com.example.rendering;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Service
public class HtmlImageService {
public byte[] renderFirstPagePng(String html, float dpi) throws IOException {
if (html == null || html.isBlank()) {
throw new IllegalArgumentException("html must not be blank");
}
if (dpi <= 0) {
throw new IllegalArgumentException("dpi must be positive");
}
byte[] pdf;
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.useFastMode();
builder.withHtmlContent(html, null);
builder.toStream(output);
builder.run();
pdf = output.toByteArray();
}
try (PDDocument document = PDDocument.load(new ByteArrayInputStream(pdf));
ByteArrayOutputStream png = new ByteArrayOutputStream()) {
if (document.getNumberOfPages() == 0) {
throw new IOException("The renderer produced no pages");
}
PDFRenderer renderer = new PDFRenderer(document);
renderer.renderImageWithDPI(0, dpi, ImageType.RGB)
.compress(null, png);
return png.toByteArray();
}
}
}
PDFBox APIs can differ between major releases. If your selected release does not expose the exact image-writing overload shown above, obtain the BufferedImage returned by renderImageWithDPI and write it with ImageIO.write(image, "PNG", output). The underlying process remains the same: HTML renderer to PDF, then PDFBox rasterization.
Rank #2
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Expose a REST endpoint
package com.example.rendering;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@RequestMapping("/render")
public class HtmlImageController {
private final HtmlImageService service;
public HtmlImageController(HtmlImageService service) {
this.service = service;
}
@PostMapping(value = "/png", consumes = MediaType.TEXT_HTML_VALUE,
produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<byte[]> png(@RequestBody String html,
@RequestParam(defaultValue = "144") float dpi)
throws IOException {
byte[] image = service.renderFirstPagePng(html, dpi);
return ResponseEntity.ok()
.cacheControl(CacheControl.noStore())
.contentType(MediaType.IMAGE_PNG)
.body(image);
}
}
Send HTML with a Content-Type: text/html request. A multi-page document still produces only page zero in this example. To return every page, loop from zero to document.getNumberOfPages() - 1 and write separate files or package the images in a ZIP.
Make the template renderer-friendly
- Use well-formed markup and provide explicit page dimensions and margins in CSS.
- Prefer supported, simple layout techniques over flexbox and grid.
- Use absolute or class-based paths for images and fonts that the renderer can resolve.
- Do not rely on JavaScript to insert content; OpenHTMLtoPDF does not execute it.
- Keep remote resources controlled and predictable. A missing font or image can change line wrapping and therefore the final dimensions.
When JavaFX WebView is the better fit
JavaFX WebView is an embedded browser for local and remote HTML. Its WebEngine handles JavaScript execution, so it is a candidate for script-dependent templates and browser-oriented markup. Oracle’s WebView overview documents those capabilities at Oracle’s JavaFX WebView documentation.
Do not assume that a desktop WebView automatically works in a minimal Linux container. Confirm JavaFX modules, fonts, display/headless support, process isolation, and lifecycle behavior on the exact operating system used in production. The cited JavaFX overview is JavaFX 8 documentation and does not establish current packaging or server deployment details.
PDF intermediate versus direct image rendering
| Requirement | Prefer | Reason and limitation |
|---|---|---|
| Controlled XHTML-like template, no scripts | OpenHTMLtoPDF | Pure Java and can output PDF or images; supported CSS is narrower than a browser. |
| Natural pages, print margins, multi-page output | HTML-to-PDF then PDFBox | PDF defines pages; PDFBox controls raster format and DPI. The HTML renderer still determines fidelity. |
| JavaScript or browser behavior | JavaFX WebView or a browser service | WebEngine executes JavaScript, but deployment and headless operation require validation. |
| Exact website screenshot of a remote page | Browser screenshot API | Designed for viewport/full-page browser capture rather than constrained document layout. |
Common failures and fixes
Blank or incomplete output
Check that the input is non-empty, the document has a page, and all required resources are reachable. For OpenHTMLtoPDF, remove JavaScript-generated content and unsupported layout rules. For remote assets, supply resolvable URLs or embed the assets in a controlled way.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #3
Flexbox or grid layout collapses
This is expected when using OpenHTMLtoPDF: its README states that many modern standards, including flex and grid, are not implemented. Rewrite the template for supported layout or switch to a browser-capable renderer.
Fonts or images are missing
Use deterministic resource paths and verify permissions and network access from the application process. A server that cannot reach a font URL cannot reproduce a developer workstation’s line breaks.
Only the first page appears
The sample intentionally renders page index zero. Iterate over every page and decide whether your API should return multiple files, a ZIP, or a PDF instead.
Out-of-memory errors
Large HTML, high DPI, and full-page images consume substantial memory. Limit input size, cap DPI, process pages one at a time, and close PDDocument and streams with try-with-resources. Do not accept arbitrary untrusted HTML without reviewing resource access and denial-of-service risks.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #4
- Brand: Wiley
- Set of 2 Volumes
- A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
Different dimensions than expected
PDF page size, CSS margins, DPI, and font availability all affect raster dimensions. Define the image contract and verify representative short, long, image-heavy, and font-heavy templates.
Performance, reliability, and operational checks
- Warm the application and renderer classes before latency-sensitive work, but measure with your own templates; no universal performance figure is established here.
- Set request, resource, and overall processing limits appropriate to your workload.
- Cache stable template results only when the HTML and all dependent assets are immutable.
- Log renderer failures, page count, output bytes, and elapsed time without logging sensitive HTML.
- Test on the same Java runtime, operating system, fonts, and container image used in production.
- Validate PNG/JPEG encoding, transparency, long documents, SVG, external resources, and non-ASCII text.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. A single GET request returns PNG, JPEG, WebP, or PDF, while its capture pipeline accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.
It also supports full-page captures with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF controls, custom CSS and JavaScript, click and wait actions, request and resource blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
Use the ScreenshotNeo documentation for request options. The basic cURL call is:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
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)
Node.js:
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(`${res.status} ${await res.text()}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
The Free plan includes 1,000 shots per month with no card. Starter is $5 for 3,000 shots, Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000; yearly billing gives two months free, and every feature is on every plan. Create a free ScreenshotNeo account to start.
Best Value
Decision checklist
- Confirm whether scripts and browser behavior are required.
- Choose viewport or paginated output and define dimensions, format, and DPI.
- Test representative templates, fonts, SVG, images, long content, and external resources.
- Validate the chosen runtime in production-like containers and operating systems.
- Set input, resource, memory, timeout, and logging limits before exposing an endpoint.
- Recheck current library versions and licenses before release.
Frequently Asked Questions
Does Spring Boot have a built-in HTML-to-image converter?
No. Spring Boot supplies application infrastructure; a separate renderer such as OpenHTMLtoPDF, JavaFX WebView, or a browser screenshot service performs rendering.
Can OpenHTMLtoPDF render JavaScript, flexbox, or CSS grid?
No. Its project documentation says it does not run JavaScript and does not implement many modern standards, including flex and grid.
Why use PDFBox if the target is a PNG?
A PDF intermediate preserves paginated layout, and PDFBox provides documented rasterization controls such as image format and DPI.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

