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);
}
}