引入pom.xml依赖。
第二步gui.ava html2image 2.0.1 org.springframework.boot spring-boot-starter-freemarker
在【resources】目录下,创建一个文件夹【templates】并在该目录下创建一个ftl文件。
demo.ftl文件内容:
药品列表
| 药品名称 | 类型 |
| ${name} | ${type} |
写一个Html转换工具类。
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import gui.ava.html.Html2Image;
import gui.ava.html.renderer.ImageRenderer;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class HtmlConvertImgHelper {
Configuration configuration;
public HtmlConvertImgHelper() {
if (configuration == null) {
configuration = BeanHelper.getBean(Configuration.class);
}
}
public byte[] htmlConvertImg(String fileName, Object map, String formatType) throws IOException, TemplateException {
String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate(fileName), map);
return htmlConvertImg(htmlText, formatType);
}
public byte[] htmlConvertImg(String htmText, String formatType) throws IOException {
//最终返回的byte流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Html2Image html2Image = Html2Image.fromHtml(htmText);
ImageRenderer imageRenderer = html2Image.getImageRenderer();
BufferedImage grayPicture = imageRenderer.getBufferedImage(BufferedImage.TYPE_INT_RGB);
ImageIO.write(grayPicture, formatType, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}
第四步
写测试类测试功能是否可用。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@Slf4j
public class Test {
@org.junit.Test
public void ccc() throws IOException, TemplateException {
Map map = new HashMap<>();
map.put("name", "鹤顶红");
map.put("type", "毒药");
byte[] bytes = new HtmlConvertImgHelper().htmlConvertImg("demo.ftl", map, "png");
OutputStream os = new FileOutputStream("G:/text.png");
os.write(bytes, 0, bytes.length);
os.flush();
os.close();
}
}



