如何在 Java 中将 HTML 转换为图像

这个简短的教程旨在解释如何通过加载 HTML 文件然后将其保存为图像,如本教程中的 PNG,将 HTML 转换为 Java 中的图像。您可以设置输出图像的许多参数,包括此处演示的分辨率。为了将 HTML 编写为图像转换器,此处使用 Java 语言,但是您也可以在许多其他语言和平台上执行此任务。

在 Java 中将 HTML 转换为图像的步骤

  1. 配置项目以从 Maven 存储库添加 Aspose.HTML 以进行 HTML 到图像的转换
  2. 将新创建的或现有的 HTML 文件加载到 HTMLDocument 类对象中
  3. 实例化 ImageSaveOptions 类对象并将图像类型设置为 PNG
  4. 设置输出图像的分辨率
  5. 使用指定的保存选项将 HTML 文件转换为 PNG

将 HTML 转换为图像 Java 基于语言的步骤在此处进行了说明。您可以将必要的库添加到项目中并导入示例代码中使用的所需类。然后按照一步一步的方法加载一个 HTML 文件,定义输出图像参数,最后将其转换为所需的图像类型。

在 Java 中将 HTML 转换为图像的代码

import java.io.FileWriter;
import com.aspose.html.HTMLDocument;
import com.aspose.html.License;
import com.aspose.html.converters.Converter;
import com.aspose.html.drawing.Resolution;
import com.aspose.html.drawing.UnitType;
import com.aspose.html.rendering.image.ImageFormat;
import com.aspose.html.saving.ImageSaveOptions;
public class ConvertHtmlToImageInJava {
public static void main(String[] args) throws Exception {//main function to convert HTML to Image
// Instantiate the license to avoid water mark in the converted image
License licenseHtmlToImage = new License();
licenseHtmlToImage.setLicense("Aspose.html.lic");
// Create an HTML file locally to test the feature
String code = "<html><body><h1>This is heading h1</h1><p>Here is a paragraph enclosed in p tag</p></body></html>";
try (FileWriter fileWriter = new FileWriter("document.html"))
{
fileWriter.write(code);
}
// Load an existing HTML file to convert to image
HTMLDocument document = new HTMLDocument("document.html");
try
{
// Create ImageSaveOptions class object and initialize it with the PNG format
ImageSaveOptions pngImageoptions = new ImageSaveOptions(ImageFormat.Png);
Resolution resolution = new Resolution(300, UnitType.DPI);
pngImageoptions.setHorizontalResolution(resolution);
pngImageoptions.setVerticalResolution(resolution);
// Export HTML to PNG using the Converter.convertHTML() function
Converter.convertHTML(document, pngImageoptions, "output.png");
}
finally
{
if (document != null)
{
document.dispose();
}
}
System.out.println("Done");
}
}

此代码演示了如何使用 Java 从 HTML 生成图像,使用几行代码首先我们在本地创建了一个 HTML 文件,但这不是必需的,您也可以将任何现有的 HTML 文件加载到 HTMLDocument 类对象中。在下一步中,初始化转换过程中所需的 ImageSaveOptions 类对象,并可选择设置一些参数,如分辨率等。最终使用 Converter.convertHTML() 函数执行转换,该函数采用源 HTML 文件、图像保存选项和输出图像文件名。

在本主题中,我们观察了在 Java 中将 HTML 转换为图像的过程,但是如果您想从头开始创建丰富的 HTML 文件,请参阅 如何使用 Java 创建 HTML 文件 上的文章。

 简体中文