java 使用Html2Image将html转图片
html2image
0.9
cn.hutool
hutool-all
5.0.6
转换代码
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
String htmlstr = “<table style=“width: 700px;font-size:16px;font-family: ‘Microsoft YaHei’;” cellpadding=“0” cellspacing=“0”> ” +
" " +
" " +
" <tr style=“width: 700px;”> " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;height: 30px;” >日期 " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;border-left: 0px;height: 30px;”>“+DateUtil.format(saleOrder.getCreateTime(), “yyyy-MM-dd HH:mm:ss”)+” " +
" " +
" <tr style=“width: 700px;”> " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;height: 30px;”>交易编号 " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;border-left: 0px;height: 30px;”>“+saleOrder.getOrderCode()+” " +
" " +
" <tr style=“width: 700px;”> " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;height: 30px;”>交易类型 " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;border-left: 0px;height: 30px;”>捐赠 " +
" " +
" <tr style=“width: 700px;”> " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;height: 30px;”>交易金额 " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;border-left: 0px;height: 30px;”>“+saleOrder.getProductPrice()+” " +
" " +
" <tr style=“width: 700px;”> " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;height: 30px;”>付款人 " +
" <td style=“border:1px solid #e6e6e6;border-top:none;text-align: center;color: #666666;border-left: 0px;height: 30px;”>“+saleOrder.getUserName()+” " +
" " +
“”;
imageGenerator.loadHtml(htmlstr);
BufferedImage bufferedImage = getGrayPicture(imageGenerator.getBufferedImage());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, “jpg”, outputStream);
String base64Img = Base64.encodeBase64String(outputStream.toByteArray());
String res = “data:image/jpg;base64,” + base64Img.toString();
modelAndView.addObject(“imageres”, res);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个是用于重新设置画布背景颜色的
