java后台将html转换为图片

方法一:利用springboot的freemark生成 要考虑样式兼容问题
1.pom引入对应的包


		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-freemarkerartifactId>
		dependency>
		<dependency>
			<groupId>com.openhtmltopdfgroupId>
			<artifactId>openhtmltopdf-coreartifactId>
			<version>0.0.1-RC9version>
		dependency>
		<repositories>
		<repository>
			<id>mvnrepositoryid>
			<name>mvnrepositoryname>
			<url>https://mvnrepository.comurl>
		repository>
	repositories>

2.对应的模板 后缀名.ft 文件

DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>海报title>
head>
<body style="width: 500px; height: 800px;margin: 0;padding: 0;">
<span>${msg}span>
<img src="${img}" alt="" />
<div style="width: 100px;height: 100px;border-radius: 50%;background: rgba(255, 0, 0, 0.2);">大幅度发div>
body>
html>

3.工具类

public class FreemarkerUtils {
    private static String getTemplate(String template, Map<String,Object> map) throws IOException, TemplateException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
        String templatePath = FreemarkerUtils.class.getResource("/").getPath()+"/templates";
        cfg.setDirectoryForTemplateLoading(new File(templatePath));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        Template temp = cfg.getTemplate(template);
        StringWriter stringWriter = new StringWriter();
        temp.process(map, stringWriter);
        stringWriter.flush();
        stringWriter.close();
        String resutl = stringWriter.getBuffer().toString();
        return resutl;
    }

    public static void turnImage(String template, Map<String,Object> map, HttpServletResponse response) throws Exception {
        String html = getTemplate(template, map);

        byte[] bytes=html.getBytes();
        ByteArrayInputStream bin=new ByteArrayInputStream(bytes);
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=factory.newDocumentBuilder();
        Document document=builder.parse(bin);
        Java2DRenderer renderer = new Java2DRenderer(document,600,800);
        BufferedImage img = renderer.getImage();
        response.setContentType("image/jpeg");
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        //输出在页面
       // ImageIO.write(img, "jpg", response.getOutputStream());
       //指定下载路径
        File file=new File("D:\\zhifu\\测试.jpg");
        try {
            ImageIO.write(img, "jpg", file);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

测试方法

  public void test(HttpServletResponse response) {
        try {
            Map<String,Object> map=new HashMap<>(16);
            map.put("msg","html--生成图片测试22222");
            map.put("img","https://upload-images.jianshu.io/upload_images/912344-3054132dd6939004.png?imageMogr2/auto-orient/strip|imageView2/1/w/300/h/240");
            FreemarkerUtils.turnImage("demo.ftl",map,response);
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

第二种 将页面代码生成html在进行转化

public class PictureHtml {
    public static void main(final String[] args) throws Exception {
//html页面中需要灵活变动的值
        String headurl = "";//图片的路径不能是带有参数的 不然解析不了
        String proUrl = "";
        String qrCodeUrl = "";
        String proName="犀牛皮特质皮鞋";
        String proPrice="1000.00";
        String userName="测试";
        String html =
                "\n" +
                "\n" +
                "\n" +
                "    \n" +
                "    \n" +
                "    分享\n" +
                "    \n" +
                "\n" +
                "\n" +
                "    
\n" + "
\n" + "
\n" + " +headurl+"\"/>\n" + "
\n"
+ " "+userName+",为您安利好物\n" + "
\n"
+ "
\n" + " +proUrl+"\"/>\n" + "
\n"
+ "
¥"+proPrice+"
\n"
+ "
"+proName+"
\n"
+ "
\n" + " +qrCodeUrl+"\"/>\n" + "
\n"
+ "
识别小程序码,查看商品详情
\n"
+ "
\n"
+ "\n" + ""; //string转为inputstream流 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(html.getBytes()); File targetFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+"share1.html"); //inputstream流转为file FileUtils.copyInputStreamToFile(byteArrayInputStream, targetFile); //通过openhtmltopdf工具生成图片 final Java2DRenderer renderer = new Java2DRenderer(targetFile, 740, 1000); final BufferedImage img = renderer.getImage(); final FSImageWriter imageWriter = new FSImageWriter(); imageWriter.setWriteCompressionQuality(1.0f); imageWriter.write(img, "D:\\zhifu\\ccc.jpg");//输出路径 System.out.println("Done with rendering"); } }

你可能感兴趣的:(项目使用技术,java,html)