栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java HTML转图片(FreeMarker + html2img)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java HTML转图片(FreeMarker + html2img)

第一步

引入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();
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/838586.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号