Converting web pages into image snapshots is a frequent need when you build reporting dashboards, email newsletters, or document archives. Aspose.OCR Cloud SDK for Java provides a powerful cloud‑based library that lets you programmatically render HTML content as high‑quality JPG images. In this guide you will learn how to convert HTML to JPG in Java, covering single‑file conversion, batch processing, and performance best practices.
HTML to JPG Conversion in Java - Prerequisites and Setup
Before you start, make sure you have the following:
- Java 8 or higher installed.
- Maven or Gradle for dependency management.
- An Aspose Cloud account with APP SID and APP KEY for OCR services.
- Network access to Aspose OCR Cloud endpoints.
Add the SDK to your project using the Maven dependency below. The same coordinates are available on the download page.
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-ocr-cloud</artifactId>
<version>25.9.0</version>
</dependency>
You will also need to import the required classes and configure your credentials, as shown in the first part of the sample code.
Convert HTML to JPG in Java - Step-by-Step Walkthrough
Step 1: Load the Source Document and Configure Credentials
Create a Configuration object and set your APP SID and APP KEY. This prepares the library for authentication.
Configuration config = new Configuration();
config.setAppSid(APP_SID);
config.setAppKey(APP_KEY);
Step 2: Initialize the OCR API
Instantiate OcrApi with the configuration. The API reference is available in the official API reference.
OcrApi ocrApi = new OcrApi(config);
Step 3: Build the Conversion Request
Create a ConvertDocumentRequest, attach the HTML file, and specify jpg as the output format.
ConvertDocumentRequest request = new ConvertDocumentRequest();
request.setFile(new File(inputHtmlPath));
request.setOutputFormat("jpg");
Step 4: Execute the Conversion
Call convertDocument to perform the conversion. The response contains the JPG bytes.
ConvertDocumentResponse response = ocrApi.convertDocument(request);
Step 5: Write the JPG Bytes to Disk
Save the returned byte array to a file using a FileOutputStream.
try (FileOutputStream fos = new FileOutputStream(outputJpgPath)) {
fos.write(response.getFileData());
}
Step 6 (Optional): Batch Conversion Loop
For batch processing, iterate over all .HTML files in a folder, repeat steps 3‑5 for each file, and log the conversion result.
for (Path htmlPath : htmlFiles) {
// Build request, execute conversion, write output (same as above)
System.out.println("Converted: " + htmlPath + " -> " + outputJpgPath);
}
Convert HTML to JPG in Java - Complete Code Example
The following program demonstrates both single‑file and batch conversion using the Aspose.OCR Cloud SDK for Java.
import com.aspose.ocr.cloud.ApiException;
import com.aspose.ocr.cloud.Configuration;
import com.aspose.ocr.cloud.api.OcrApi;
import com.aspose.ocr.cloud.model.ConvertDocumentRequest;
import com.aspose.ocr.cloud.model.ConvertDocumentResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class HtmlToJpgConverter {
// Replace with your actual Aspose OCR Cloud credentials
private static final String APP_SID = "YOUR_APP_SID";
private static final String APP_KEY = "YOUR_APP_KEY";
// Single conversion example
private static void convertSingleHtml(String inputHtmlPath, String outputJpgPath) throws IOException, ApiException {
// Prepare SDK configuration
Configuration config = new Configuration();
config.setAppSid(APP_SID);
config.setAppKey(APP_KEY);
// Initialize API instance
OcrApi ocrApi = new OcrApi(config);
// Build request
ConvertDocumentRequest request = new ConvertDocumentRequest();
request.setFile(new File(inputHtmlPath));
request.setOutputFormat("jpg");
// Execute conversion
ConvertDocumentResponse response = ocrApi.convertDocument(request);
// Write the resulting JPG bytes to file
try (FileOutputStream fos = new FileOutputStream(outputJpgPath)) {
fos.write(response.getFileData());
}
}
// Batch conversion example
private static void convertBatchHtml(String inputFolder, String outputFolder) throws IOException, ApiException {
// Prepare SDK configuration
Configuration config = new Configuration();
config.setAppSid(APP_SID);
config.setAppKey(APP_KEY);
// Initialize API instance
OcrApi ocrApi = new OcrApi(config);
// Ensure output directory exists
Files.createDirectories(Paths.get(outputFolder));
// Collect all .html files from the input folder
List<Path> htmlFiles;
try (Stream<Path> walk = Files.walk(Paths.get(inputFolder))) {
htmlFiles = walk.filter(Files::isRegularFile)
.filter(p -> p.toString().toLowerCase().endsWith(".html"))
.collect(Collectors.toList());
}
// Process each file
for (Path htmlPath : htmlFiles) {
String fileNameWithoutExt = com.google.common.io.Files.getNameWithoutExtension(htmlPath.getFileName().toString());
String outputJpgPath = Paths.get(outputFolder, fileNameWithoutExt + ".jpg").toString();
// Build request
ConvertDocumentRequest request = new ConvertDocumentRequest();
request.setFile(htmlPath.toFile());
request.setOutputFormat("jpg");
// Execute conversion
ConvertDocumentResponse response = ocrApi.convertDocument(request);
// Write JPG output
try (FileOutputStream fos = new FileOutputStream(outputJpgPath)) {
fos.write(response.getFileData());
}
System.out.println("Converted: " + htmlPath + " -> " + outputJpgPath);
}
}
public static void main(String[] args) {
try {
// Example of single file conversion
convertSingleHtml("sample.html", "sample.jpg");
// Example of batch conversion
convertBatchHtml("input_html", "output_jpg");
} catch (IOException | ApiException e) {
e.printStackTrace();
}
}
}
Note: This code example demonstrates the core functionality. Before using it in your project, make sure to update any file paths and configuration values to match your actual environment, verify that all required dependencies are properly installed, and test thoroughly in your development environment. If you encounter any issues, please refer to the official documentation or reach out to the support team for assistance.
HTML to JPG Conversion via REST API Using cURL
If you prefer a pure REST approach, the same conversion can be performed with cURL commands. The workflow consists of authentication, file upload, conversion request, and downloading the result.
1. Authenticate and Get Access Token
Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your credentials.
curl -X POST "https://api.aspose.cloud/connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
The response contains an access_token you will use in subsequent calls.
2. Upload the Source HTML File
Assuming you saved the token in a variable $TOKEN.
curl -X POST "https://api.aspose.cloud/v4.0/ocr/upload" \
-H "Authorization: Bearer $TOKEN" \
-F "file=@sample.html"
The upload returns a fileId that identifies the stored document.
3. Execute the Conversion
Request conversion to JPG.
curl -X POST "https://api.aspose.cloud/v4.0/ocr/convert?outputFormat=jpg&fileId=$FILE_ID" \
-H "Authorization: Bearer $TOKEN"
The response body contains the JPG binary data.
4. Download the Output File
Save the binary stream to a local file.
curl -X GET "https://api.aspose.cloud/v4.0/ocr/download?fileId=$FILE_ID&format=jpg" \
-H "Authorization: Bearer $TOKEN" \
-o sample.jpg
For more details on request parameters and error handling, see the official API documentation.
Conclusion
Converting HTML to JPG in Java is straightforward with the Aspose.OCR Cloud SDK for Java. By following the setup steps, using the provided code samples, or invoking the REST API with cURL, you can generate image previews for any web content quickly and reliably. Remember to obtain a proper license for production deployments; pricing details are available on the product page, and you can request a temporary license from the temporary license page. Start integrating HTML‑to‑JPG conversion today and enhance the visual experience of your applications.
FAQs
-
How do I convert HTML to JPG in Java without writing a lot of code?
Use the one‑liner shown in the walkthrough: create aConvertDocumentRequest, set the file andoutputFormatto"jpg", then callocrApi.convertDocument(request). The SDK handles rendering and returns the JPG bytes. -
Can I batch convert HTML files to JPG in Java?
Yes. TheconvertBatchHtmlmethod in the example walks a directory, creates a request for each.HTMLfile, and writes each JPG output. This approach scales well for large collections. -
What Java code converts HTML to JPG?
The complete code example above demonstrates the exact Java code needed. It includes credential configuration, request building, execution, and file writing. -
Is there a way to test the conversion before purchasing a license?
You can obtain a temporary license from the temporary license page to evaluate the library without cost during development.
Read More
- Convert PDF file to images and recognize text using Aspose Cloud APIs
- Convert workbook elements to images and extract text from images using Aspose Cloud REST APIs
- New Release of Aspose.OCR Cloud SDK for Java - A Cloud SDK to Extract OCR or HOCR Text from Images in Java Using Powerful Aspose.OCR Cloud APIs