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

<!-- html生成图片--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><dependency><groupId>com.openhtmltopdf</groupId><artifactId>openhtmltopdf-core</artifactId><version>0.0.1-RC9</version></dependency><repositories><repository><id>mvnrepository</id><name>mvnrepository</name><url>https://mvnrepository.com</url></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 ="<!DOCTYPE html>\n" +"<html lang=\"en\">\n" +"<head>\n" +"    <meta charset=\"UTF-8\"/>\n" +"    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n" +"    <title>分享</title>\n" +"    <style>\n" +"        body {\n" +"            font-size: 0;\n" +"            padding: 0;\n" +"            margin: 0;\n" +"        }\n" +"\n" +"        div {\n" +"            box-sizing: border-box;\n" +"        }\n" +"\n" +"        .main {\n" +"            width: 654px;\n" +"            margin: 0 auto;\n" +"            padding: 28px;\n" +"            text-align: center;\n" +"            background: green;\n" +"        }\n" +"\n" +"        .top{\n" +"            display: inline-block;\n" +"            max-width: 100%;\n" +"            margin: 0 auto 20px;\n" +"            position: relative;\n" +"            padding-left: 56px;\n" +"            font-size: 28px;\n" +"            line-height: 48px;\n" +"            color: #666;\n" +"        }\n" +"\n" +"        .oneOver {\n" +"            overflow: hidden;\n" +"            text-overflow: ellipsis;\n" +"            white-space: nowrap;\n" +"        }\n" +"\n" +"        .head{\n" +"            height: 48px;\n" +"            width: 48px;\n" +"            border-radius: 50%;\n" +"            overflow: hidden;\n" +"            border: solid 1px #E6E6E6;\n" +"            position: absolute;\n" +"            left: 0;\n" +"            top: 0;\n" +"            overflow: hidden;\n" +"        }\n" +"\n" +"        .head img {\n" +"            width: 100%;\n" +"            height: 100%;\n" +"        }\n" +"\n" +"        .pro_pic{\n" +"            width: 400px;\n" +"            height: 400px;\n" +"            margin: 0 auto 24px;\n" +"        }\n" +"\n" +"        .pro_pic_{\n" +"            width: 100%;\n" +"            height: 100%;\n" +"        }\n" +"\n" +"        .money{\n" +"            font-size: 40px;\n" +"            font-weight: bold;\n" +"            padding-bottom: 16px;\n" +"        }\n" +"\n" +"        .name{\n" +"            font-size: 28px;\n" +"            line-height: 40px;\n" +"            font-weight: bold;\n" +"            padding-bottom: 34px;\n" +"        }\n" +"\n" +"        .code{\n" +"            height: 175px;\n" +"            width: 175px;\n" +"            margin: 0 auto 20px;\n" +"            border: solid 1px #E6E6E6;\n" +"            border-radius: 50%;\n" +"            overflow: hidden;\n" +"        }\n" +"\n" +"        .code_pic{\n" +"            height: 175px;\n" +"            width: 175px;\n" +"        }\n" +"\n" +"        .desc{\n" +"            font-size: 24px;\n" +"            line-height: 34px;\n" +"            color: #999;\n" +"        }\n" +"    </style>\n" +"</head>\n" +"<body>\n" +"    <div class=\"main\" id=\"main\">\n" +"        <div class=\"top oneOver\">\n" +"            <div class=\"head\">\n" +"                <img class=\"persion_pic\" src=\""+headurl+"\"/>\n" +"            </div>\n" +"            "+userName+",为您安利好物\n" +"        </div>\n" +"        <div class=\"pro_pic\">\n" +"            <img class=\"pro_pic_\" src=\""+proUrl+"\"/>\n" +"        </div>\n" +"        <div class=\"money\">¥"+proPrice+"</div>\n" +"        <div class=\"name\">"+proName+"</div>\n" +"        <div class=\"code\">\n" +"            <img class=\"code_pic\" src=\""+qrCodeUrl+"\"/>\n" +"        </div>\n" +"        <div class=\"desc\">识别小程序码,查看商品详情</div>\n" +"    </div>\n" +"</body>\n" +"</html>";
//string转为inputstream流ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(html.getBytes());File targetFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+"share1.html");
//inputstream流转为fileFileUtils.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转换为图片相关推荐

  1. java后台生成图片(加载外部字体)

    Java后台生成图片: 自定义图片内文字和图片位置. 可背景透明. 字体尺寸.颜色.间距等基本设置和透明度设置. 文本换行与居中. 加载外部字体. 原理 使用java图形化工具绘制图片. 注意:lin ...

  2. java pdf 多页转换为png格式的图片

    java pdf 多页转换为png格式的图片  适用于 无论pdf有多少页均可 废话不说,直接上代码 import java.awt.Graphics; import java.awt.image.B ...

  3. java html 转图片_Java HTML转换为图片

    第一次尝试:用awt 包将HTML源码转换为图片 优点:不依赖任何外部JAR包,缺点:对CSS的支持比较差,复杂点的样式就无法展示,且不支持外部引入的CSS和写在style中的CSS,只能写在标签上 ...

  4. java后台保存base64图片数据

    java后台保存base64图片数据 使用byte[] bytes = new BASE64Decoder().decodeBuffer(str);需要引入sun.misc.BASE64Decoder ...

  5. 微信小程序图片上传到java后台

    前言 关于云存储的文件上传,我想说的真的挺多的,这是一篇纯原创的基于小程序 或者是SpringBoot的云存储的全过程. 整篇教学很细很细,适合于所有的java学习者,特别是刚刚结束学习java想要练 ...

  6. Java中将base64编码字符串转换为图片

    前一段时间,在做摄像头拍照上传,摄像头拍的照片为base64编码格式的字符串,需要上传至项目中,则需要使用到将base64编码字符串转换为图片 1.将base64编码字符串转换为图片的代码如下 Ima ...

  7. Java后台生成图表——主代码(折线图,饼状图,柱状图,-》并产出图片PDF或其他格式的图片内容)

    声明: 本文采用的数据均来源于网络,本人只用于学习记录,若有侵权,还望能及时联系. Maven 的 POM 依赖 <!--必要--><!--用于jfreechart生成图片 --&g ...

  8. java pdf转图片拼接_java实现pdf按页转换为图片

    本文实例为大家分享了java实现pdf按页转换为图片的具体代码,供大家参考,具体内容如下 本程序是利用jacob.jar包实现的,关于jacob.jar的配置见我上一篇文章,程序中可配置参数选择图片清 ...

  9. java pptx转图_Java如何将PPT的幻灯片转换为图片?

    在Java编程中,如何将PPT的幻灯片转换为图片? 注意:需要访问网址: , 下载一个Apache POI软件包.这里下载最新版本:poi-bin-3.17-20170915.tar.gz解压并全部导 ...

最新文章

  1. pHp封装成vue,vue.js生成条形码的方法
  2. THINKPAD笔记本Fn组合键介绍
  3. Upwork 发布最赚钱的编程语言 Top 15
  4. Spring Cloud Stream消费失败后的处理策略(三):使用DLQ队列(RabbitMQ)
  5. python起步输入-[转载]python核心编程学习笔记-python起步
  6. libqrencode生成二维码图片的问题
  7. 一个操作系统的实现(1)
  8. Python里那些可爱的游戏模块们
  9. 国外基于android的系统,基于Android的位置服务系统设计与实现
  10. MySQL常用权限的解释
  11. SLS控制台内嵌操作指南
  12. 服务器维护经验分享,医院IT运维经验分享.pdf
  13. 杠上谷歌,微软利用人工智能加码必应搜索的市场竞争力
  14. 【iphone】 如何将app发布到appstore中
  15. c4d阿诺德渲染器支持a卡吗_请问C4D的OC渲染器支持的显卡是越好越快吗?
  16. Total Control通过定义配置文件,预加载脚本教程
  17. aspnetpager 详解
  18. Python使用requests设置headers、cookies实现猫眼实时电影票房排行榜爬取
  19. echarts字体大小自适应
  20. MySQL 插入语句

热门文章

  1. 从程序员创业谈起--对话周鸿祎
  2. 脑筋..柔软性? flexibility? 灵活性? 头脑体操?
  3. java单链表通讯录_[Java教程]用java实现单链表(菜鸟出征)
  4. html 去除li标签样式,CSS如何更改li标签样式?附源码!
  5. 啥是面向对象?啥是封装、继承、多态?看看这篇文章就够了
  6. 【python】对象释放,弱引用weaker.ref
  7. scrapy shell list crawl 命令行无显示退出 no echo quit scrapy 踩坑
  8. 小程序实现天/时/分/秒倒计时效果
  9. 视频处理之视频抽帧的python脚本
  10. 通过变量指定少量用户实现AB测试(灰度测试):split_client模块