Java HTML转成图片

web应该开发中有时会遇到生成图片的场景,下面提供一种有HTML模板生成图片的方法。

1、引入依赖

<dependency>
    <groupId>freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.8</version>
</dependency>
<dependency>
    <groupId>gui.ava</groupId>
    <artifactId>html2image</artifactId>
    <version>0.9</version>
</dependency>

其中freemarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写。freemarker被设计用来生成HTML Web页面,特别是基于MVC模式的应用程序。
html2image是一个运行在Linux/Unix平台上将网页转化为图片的工具,它能将网页转化为bmp、png和jpg等格式的图片。

2、模板文件

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        table tr td {
            border: 1px solid #000000;
            text-align: center;
            font-size: 16px;
        }
        #container {
            margin: 20px;
            width: 750px;
            height: 1000px;
        }
        #title {
            text-align: center;
            font-weight: bold;
            padding: 18px;
            font-size: 25px;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="title">XXX申请表</div>
        <table width="100%" cellspacing="0">
            <tbody>
                <tr>
                    <td style="width: 15%">姓名</td>
                    <td style="width: 15%">${name}</td>
                    <td style="width: 15%">年龄</td>
                    <td style="width: 15%">${age}</td>
                    <td style="width: 20%">是否已婚</td>
                    <td style="width: 20%">
                        <#if marry == "1">☑ <#else></#if>&nbsp;&nbsp;&nbsp;&nbsp;
                        <#if marry == "0">☑ <#else></#if></td>
                </tr>
                <tr>
                    <td colspan="6">
                        其他内容……
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

3、文件工具类

public class FileUtil {

    /**
     * 获取资源路径
     * @return
     */
    public static String getResourcePath(String fileP){
        String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""));	//项目路径
        filePath = filePath.replaceAll("file:/", "");
        filePath = filePath.replaceAll("%20", " ");
        filePath = filePath.trim() + fileP.trim();
        if(filePath.indexOf(":") != 1){
            filePath = File.separator + filePath;
        }

        return filePath;
    }
}

4、图片工具类

import com.xmotor.util.FileUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import gui.ava.html.image.generator.HtmlImageGenerator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class ImageUtil {

    private static Configuration cfg;

    static {
        try {
            //初始化FreeMarker配置
            cfg = new Configuration();
            //设置FreeMarker的模版文件位置
            cfg.setDirectoryForTemplateLoading(new File(FileUtil.getResourcePath("") + "ftl"));
            cfg.setDefaultEncoding("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取模板
     * @param templateName 模板名,如test.ftl
     * @return
     */
    public static Template getTemplate(String templateName) {
        Template t = null;
        try {
            t = cfg.getTemplate(templateName);
            t.setEncoding("UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * HTML转图片
     * @param outputPath 输出路径
     * @param imageName 图片名称
     * @param data 填充数据
     * @param template html模板
     * @return
     */
    private static String htmlToImage(String outputPath, String imageName, Map<String,String> data, Template template){
        if (template == null){
            throw new RuntimeException("The template is not found ...");
        }

        File file = new File(outputPath);
        if (file.exists()) {
            if (!file.isDirectory()){
                throw new RuntimeException("The parameter 'outputPath' is not a folder ...");
            }
        }else {
            file.mkdirs();
        }

        try {
            String outputFile = outputPath + File.separator + imageName + ".png";
            StringWriter stringWriter = new StringWriter();
            BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
            template.process(data, bufferedWriter);
            bufferedWriter.flush();
            bufferedWriter.close();

            HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
            imageGenerator.loadHtml(stringWriter.toString());
            imageGenerator.saveAsImage(outputFile);
            return outputFile;
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

5、测试

public static void main(String[] args) {
    Template t = ImageUtil.getTemplate("test.ftl");
    String outputPath = "C:\\Users\\admin\\Desktop\\TestHtmlToImage\\测试";
    Map<String,String> data = new HashMap<String,String>();
    data.put("name", "王二狗");
    data.put("age", "20");
    data.put("marry", "1");
    String result = ImageUtil.htmlToImage(outputPath, "test", data, t);
    System.out.println(result);
}

在这里插入图片描述

6、在SpringBoot项目中的使用

上面.setDirectoryForTemplateLoading()方法在传统的web工程中使用没问题,但在SpringBoot项目中使用会有问题,具体原因待求解
在这里插入图片描述
解决方法如下:

<!--springboot集成的freemarker-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--html转图片工具-->
<dependency>
    <groupId>gui.ava</groupId>
    <artifactId>html2image</artifactId>
    <version>0.9</version>
</dependency>

freemarker的配置采用ClassTemplateLoader加载:

try {
    //初始化FreeMarker配置
    cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    cfg.setDefaultEncoding(Charset.forName("UTF-8").name());
    cfg.setTemplateLoader(new ClassTemplateLoader(ImageGenerateManager.class, "/templates/"));
} catch (Exception e) {
    log.error("Init template configuration error ...");
    e.printStackTrace();
}

其中"/templates/"是绝对路径写法,会在项目根目录下开始查找模板,"templates/"是相对路径写法,会在该类所在的目录下开始查找模板。
上面采用绝对路径写法,模板放在resources目录下:
在这里插入图片描述
图片生成功能封装类:

package com.xmotor.boot.plugin.toolkit.image;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import gui.ava.html.image.generator.HtmlImageGenerator;
import lombok.extern.slf4j.Slf4j;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Map;
/**
 * 图片生成器,HTML转图片
 */
@Slf4j
public class ImageGenerateManager {
    private Configuration cfg;

    public ImageGenerateManager() {
        try {
            //初始化FreeMarker配置
            cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            cfg.setDefaultEncoding(Charset.forName("UTF-8").name());
            cfg.setTemplateLoader(new ClassTemplateLoader(ImageGenerateManager.class, "/templates/"));
        } catch (Exception e) {
            log.error("Init template configuration error ...");
            e.printStackTrace();
        }
    }

    /**
     * 获取模板
     * @param templateName 模板名,如test.ftl
     * @return
     */
    private Template getTemplate(String templateName) {
        Template t = null;
        try {
            t = cfg.getTemplate(templateName);
        } catch (IOException e) {
            log.error("Get html template error ...");
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 获取Html2Image图片生成器
     * @param tplName
     * @param data
     * @return
     */
    private HtmlImageGenerator getHtmlImageGenerator(String tplName, Map<String,String> data){
        Template template = getTemplate(tplName);
        if (template == null){
            throw new RuntimeException("The template is not found ...");
        }

        try {
            StringWriter stringWriter = new StringWriter();
            BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
            template.process(data, bufferedWriter);
            bufferedWriter.flush();
            bufferedWriter.close();
            HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
            imageGenerator.loadHtml(stringWriter.toString());
            return imageGenerator;
        } catch (TemplateException | IOException e) {
            log.error("Get generator error ...");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * HTML转图片
     * @param tplName 模板名称,如test.ftl
     * @param data 填充数据
     * @param outputPath 输出路径,如D:\测试\HtmlToImage测试\XXX申请表.png
     * @return
     */
    public void html2Image(String tplName, Map<String,String> data, String outputPath){
        HtmlImageGenerator generator = getHtmlImageGenerator(tplName, data);
        if (generator == null){
            throw new RuntimeException("The generator is not found ...");
        }
        generator.saveAsImage(outputPath);
    }

    /**
     * HTML转图片
     * @param tplName 模板名称,如test.ftl
     * @param data 填充数据
     * @return
     */
    public BufferedImage html2Image(String tplName, Map<String,String> data){
        HtmlImageGenerator generator = getHtmlImageGenerator(tplName, data);
        if (generator == null){
            throw new RuntimeException("The generator is not found ...");
        }
        return generator.getBufferedImage();
    }


}

装配类:

@Configuration
@ConditionalOnClass({ImageGenerateManager.class, ImageMergeManager.class})
public class ImageAutoConfiguration {

    @Bean
    @ConditionalOnProperty(prefix = "xmotor.boot.toolkit.image-generate", name = {"enabled"}, havingValue = "true", matchIfMissing = false)
    public ImageGenerateManager getImageGenerateManager() {
        return new ImageGenerateManager();
    }
}

springboot配置:

xmotor.boot.toolkit.image-generate.enabled=true

使用:

@Slf4j
@RestController
@RequestMapping("/TestImageManager")
public class TestImageManagerController extends BaseController {

    @Autowired
    private ImageGenerateManager imageGenerateManager;

    @Autowired
    private IUploader uploader;
    
    @RequestMapping("/test2")
    public Result<FileUrl> test2() throws Exception{
        Map<String,String> data = new HashMap<String,String>();
        data.put("name", "王二狗");
        data.put("age", "20");
        data.put("marry", "1");
        String tplName = "ftl/test.ftl";
        BufferedImage image = imageGenerateManager.html2Image(tplName, data);
		
		//上传
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        InputStream is = new ByteArrayInputStream(os.toByteArray());
        FileUrl path = uploader.upload(is,os.size());
        return ok(path);
    }
}

参考:freemaker模板位置ClassTemplateLoader的绝对路径相对路径设置方法

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alex·Guangzhou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值