JAVA html转图片,带css样式,亲测有效

Maven加依赖

<dependency>
	<groupId>org.xhtmlrenderer</groupId>
	<artifactId>flying-saucer-pdf</artifactId>
	<version>9.8.0</version>
</dependency>

压缩代码

import org.xhtmlrenderer.simple.Graphics2DRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;

public class Html2ImageUtil {

    /**
     * html转图片并保存在本地,返回本地文件
     * @param html
     * @return
     */
    public static File html2Image(String html, String saveDir) throws IOException {
        // 先将html写入临时文件,注意:此时的html包含渲染html必须的元素,如<html><body>等标签
        File source = html2File(html, saveDir);
        try {
            String savePath = saveDir + (saveDir.endsWith(File.separator) ? "" : File.separator) + UUID.randomUUID() + ".png";
            BufferedImage bufferedImage = Graphics2DRenderer.renderToImage(source.toURI().toURL().toExternalForm(), 1024, 2000);
            File file = new File(savePath);
            ImageIO.write(bufferedImage, "png", file);
            return file;
        } finally {
            source.deleteOnExit();
        }
    }

    private static File html2File(String html, String tmpDir) throws IOException {
        String savePath = tmpDir + (tmpDir.endsWith(File.separator) ? "" : File.separator) + UUID.randomUUID() + ".html";
        FileWriter fileWriter = new FileWriter(savePath);
        BufferedWriter writer = new BufferedWriter(fileWriter);
        writer.write(html);
        writer.close();
        fileWriter.close();
        return new File(savePath);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值