html转成图片

依赖

XML 复制代码
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.13.1</version>
</dependency>
java 复制代码
import org.aspectj.util.FileUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class HtmlToImage {

    public static void main(String[] args) throws IOException {

        String outPath = "D:\\work\\project\\jar\\wordtopdf-server\\createWordBytemplate\\src\\test\\java\\simple.png";
        String htmlTemplateStr = "D:\\work\\project\\jar\\wordtopdf-server\\createWordBytemplate\\src\\test\\java\\simple.html";
        String html = FileUtil.readAsString(new File(htmlTemplateStr));

//        String html = "<html><body>Hello, World!<p>This is a simple HTML to Image example.</p></body></html>";
        try {
            BufferedImage image = createImageFromHtml(html);
            ImageIO.write(image, "png", new File(outPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage createImageFromHtml(String html) {
        Document doc = Jsoup.parse(html);
        String text = doc.body().text();

        // Create a BufferedImage
        BufferedImage bufferedImage = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();
        
        // Set Background Color
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, 800, 600);

        // Set Text properties
        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("Arial", Font.PLAIN, 24));

        // Draw Text
        g2d.drawString(text, 50, 50);
        g2d.dispose();

        return bufferedImage;
    }
}

【Java利用poi-tl实现富文本HTML转Word - CSDN App】https://blog.csdn.net/wdy_2099/article/details/117951909?sharetype=blog\&shareId=117951909\&sharerefer=APP\&sharesource=m0_49128301\&sharefrom=link

相关推荐
这是程序猿1 天前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
i***t9191 天前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
k***08291 天前
【监控】spring actuator源码速读
java·spring boot·spring
q***47181 天前
Spring中的IOC详解
java·后端·spring
DKPT1 天前
ZGC和G1收集器相比哪个更好?
java·jvm·笔记·学习·spring
Hollis Chuang1 天前
Spring Boot 4.0 正式发布,人麻了。。。
java·spring boot·后端·spring
椎4951 天前
苍穹外卖资源点整理+个人错误解析-Day10-订单状态定时处理(Spring Task)、来单提醒和客户催单
java·后端·spring
Y***h1871 天前
eclipse配置Spring
java·spring·eclipse
p***62991 天前
CVE-2024-38819:Spring 框架路径遍历 PoC 漏洞复现
java·后端·spring