当前位置: 首页 > 工具软件 > Html2Image > 使用案例 >

html2image使用

沈飞翼
2023-12-01
实例代码
File file = new File(scjkConfig.getApkPath()+"temp/");
  if (!file.exists()) {
      file.mkdirs();
  }
  String pic_path = scjkConfig.getApkPath()+"temp/"+waterPlants.getId()+".png";
  try{
      String filePath = waterModel.getPath().replace("/files/", "");
      String url = scjkConfig.getUploadPath()+filePath;
      File templateFile = new File(url);
      //读取文件
       String content = FileUtils.readFileToString(templateFile, "utf-8");
      //创建一个解析器
      Document doc = Jsoup.parse(content);
      Element body = doc.body();
      body.attr("style","width:1366px;height:768px;");
      Elements es_template = doc.getElementsByClass("template");
      Element template = es_template.get(0);
      //java.net.URLEncoder.encode(basePath+waterModel.getImagePath(), "GBK");
      template.attr("style","background-image:url('"+basePath+waterModel.getImagePath()+"');background-repeat:no-repeat");
      Elements es_technology = doc.getElementsByClass("technology");
      Iterator it = es_technology.iterator();
      if(StringUtils.isNotNull(waterModel.getTemplateIds())){
      while(it.hasNext()) {
          Element element = (Element) it.next();
           element.attr("style","border:none;");
          String divId =  element.attr("id");
          String[] tid_did = waterModel.getTemplateIds().split(",");
          for(String tdId:tid_did){
              String tid =  tdId.substring(0,tdId.indexOf("-"));
              String did =  tdId.substring(tdId.indexOf("-")+1,tdId.length());
              if(divId.equals(did)){
                  for(TemplateModel tm:tms){
                      if(tid.equals(tm.getId()+"")){
                          element.html("<div style=\"background:#2E6B87;color:white;min-height:25px;line-height:25px;padding:2px;text-align:center;border-radius:5px;font-size:13px;\">"+tm.getName()+"<span style=\"color:#3FD5F5;\">"+tm.getValuez()+"</span>"+tm.getUnit()+"</div>");
                      }

                  }

              }
          }
      }

      }
       html2Image = Html2Image.fromHtml(doc.html());
      System.out.println(doc.html());
       //html2Image = Html2Image.fromHtml(document.toString());
  }catch (Exception e){
      System.out.print(e);
  }

if(html2Image!=null){
    html2Image.getImageRenderer().saveImage(pic_path);
}
  waterModel.setImagePath(pic_path.replaceAll(scjkConfig.getApkPath(),"/appFiles/"));
  result.put("waterModel",waterModel);

2、注意事项

找不到类错误就是jar包不符合,可到github官网代码里找到pom文件引入相应的子jar版本
jsoup爬虫得到html的内容

 类似资料: