方法一:html2Image
1、引入依赖
<dependency>
<groupId>gui.ava</groupId>
<artifactId>html2image</artifactId>
<version>2.0.1</version>
</dependency>
2、代码实现
@Component
public class HtmlUtil {
/**
* 文件工具
*/
@Autowired
private FileUtil fileUtil;
public String htmlToImageConverter(String html, Integer height, Integer width, String fileName) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
HtmlParserImpl htmlParser = new HtmlParserImpl();
htmlParser.loadHtml(html);
ImageRendererImpl imageRenderer = new ImageRendererImpl(htmlParser);
//设置宽高,未设置自动适应
if(height != null){
imageRenderer.setHeight(height);
}
if(width != null){
imageRenderer.setWidth(width);
}
BufferedImage bufferedImage = imageRenderer.getBufferedImage();
//默认png格式,jpg格式会出现渲染问题,需要重写ImageRendererImpl
// 这里是因为他这边写死图片的压缩算法为BufferedImage.BITMASK,修改成BufferedImage.TYPE_INT_RGB即可
try {
ImageIO.write(bufferedImage, "png", outputStream);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
// 将图像保存为PNG格式的文件
FileItem fileItem = CommUtil.createFileItem(byteArrayInputStream, fileName + ".png");
//上传到文件服务并获取文件ID
fileId = fileUtil.getFileId(fileItem);
outputStream.close();
byteArrayInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fileId;
}
}
存在问题
1、渲染的html界面和实际界面存在出入,例如设置
宽度,如果内容长度超过宽度,会换行,而使用html2Image渲染出来的界面只有一行。方式二:selenium+phantomJS
实现方式
1、安装phantomJS插件
2、引入依赖
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
<exclusion>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.codeborne</groupId>
<artifactId>phantomjsdriver</artifactId>
<version>1.4.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>25.0-jre</version>
</dependency>
标签:outputStream,JAVA,selenium,imageRenderer,html,new,guava,转为
From: https://www.cnblogs.com/IamHzc/p/17408112.html