package com.dawn.ruanzhupro;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
@SpringBootTest
public class HTML2ImgTest {
public static void main(String[] args) {
// // 指定 HTML 文件路径
// String filePath = "D:\\test\\java\\com\\dawn\\ruanzhupro\\test.html"; // 请替换为你的 HTML 文件路径
// // 读取 HTML 文件内容到 htmlContent 变量
// String htmlContent = readHtmlFile(filePath);
// 指定 HTML 文件路径
String filePath = "D:\\Codexxxxxxxx\\src\\test\\javaxxxx\\test.html"; // 请替换为你的 HTML 文件路径
// 读取 HTML 文件内容到 htmlContent 变量
String htmlContent = readHtmlFile(filePath);
String apiUrl = "http://xx.xx.xx.xx:3000/convert"; // Node.js 服务地址
// 转义 HTML 内容
String escapedHtmlContent = escapeHtmlForJson(htmlContent);
// 构建 JSON 字符串
String jsonInputString = "{\"htmlContent\": \"" + escapedHtmlContent + "\"}";
System.out.println("请求的 JSON 数据:");
System.out.println(jsonInputString); // 打印出实际发送的 JSON 数据,确保格式正确
try {
// 创建 URL 对象
URL url = new URL(apiUrl);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
// 发送请求数据
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
// 获取响应
int status = connection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
System.out.println("HTML 转换为图片成功!");
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream("output_image.png");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
inputStream.close();
outputStream.close();
System.out.println("图片已保存为 output_image.png");
} else {
System.out.println("请求失败,状态码:" + status);
} catch (IOException e) {
e.printStackTrace();
// 读取 HTML 文件内容
public static String readHtmlFile(String filePath) {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n"); // 逐行读取文件内容
} catch (IOException e) {
e.printStackTrace();
return null;
return content.toString();
// 转义 HTML 内容为 JSON 格式
public static String escapeHtmlForJson(String html) {
return html.replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "").replace("\t", ""); // 去除换行符和转义字符