java使用phantomjs生成证书图片

学习链接

phantomjs说明文档

下载phantomjs

到官网下载系统对应的phantomjs:https://phantomjs.org/download.html
在这里插入图片描述

在windows环境下解压phantomjs

直接解压即可,并配置环境变量
在这里插入图片描述

在linux环境下解压phantomjs

tar -jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2
mv phantomjs-2.1.1-linux-x86_64 phantomjs

在这里插入图片描述

下载nodejs,并安装

phantomjs命令的运行,需要借助node环境,因此需要安装nodejs

1、window环境安装nodejs,一步步安装即可;
2、如果是在linux环境下,可参考这篇:Linux服务器安装NodeJs简易方法

html2pdf.js

var page = require('webpage').create();
var system = require('system');

读取命令行参数,也就是js文件路径。
if (system.args.length === 1) {
  console.log('Usage: loadspeed.js <some URL>');
//这行代码很重要。凡是结束必须调用。否则phantomjs不会停止
  phantom.exit();
}
page.settings.loadImages = true;  //加载图片
page.settings.resourceTimeout = 30000;//超过10秒放弃加载
//截图设置,
//page.viewportSize = {
//  width: 1000,
//  height: 3000
//};
var address = system.args[1];
page.open(address, function(status) {

    function checkReadyState() {//等待加载完成将页面生成pdf
        setTimeout(function () {
            var readyState = page.evaluate(function () {
                return document.readyState;
            });

            if ("complete" === readyState) {

                page.paperSize = { width:'1500px',height:'2000px',orientation: 'portrait',border: '1cm' };
                var timestamp = Date.parse(new Date());
                var pdfname = 'HT_'+timestamp + Math.floor(Math.random()*1000000);
                // var outpathstr = "d:/projects/demo-cert/src/main/resources/"+pdfname+".png";
                var outpathstr = "/root/phantomjs/images/"+pdfname+".png";
                page.render(outpathstr);
                //page.render("c://test.png");
                //console.log就是传输回去的内容。
                console.log("生成成功");
                console.log("$"+outpathstr+"$");
                phantom.exit();

            } else {
                checkReadyState();
            }
        },1000);
    }
    checkReadyState();
});

使用phantomjs命令生成图片

windows环境

在这里插入图片描述

linux环境

使用本地的html文件,生成该html文件的图片

/root/phantomjs/bin/phantomjs /root/phantomjs/bin/html2pdf.js file:///root/phantomjs/html/test.html

在这里插入图片描述
查看生成的图片
在这里插入图片描述

phantomjs执行常见错误
执行phantomjs命令报错

参照:https://www.cnblogs.com/ldbangel/p/9761875.html

一:在服务器迁移之后发现,phantomjs截图没有执行,但是服务也没有报错(确认phantomjs相关路径没有问题)
二:测试

1、编写一个测试脚本test.js

console.log('Hello, world!');
phantom.exit();

2、使用phantomjs执行测试脚本,出现如下错误

[root@VM_4_4_centos opt]# /opt/phantomjs/bin/phantomjs /opt/test.js 
/opt/phantomjs/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: 
cannot open shared object file: No such file or directory

三:解决方法

yum -y install freetype
yum -y install fontconfig

然后执行测试脚本显示正常

[root@VM_4_4_centos opt]# /opt/phantomjs/bin/phantomjs /opt/test.js 
Hello, world!
插入的中文没有显示

phantomjs linux 中文不显示,linux 安装phantomJs 用于截图,处理中文乱码,和样式问题…
执行命令:yum install bitmap-fonts-cjk

使用java代码生成图片demo

ImgController

@SuppressWarnings("all")
@RestController
@RequestMapping("img")
public class ImgController {

    @GetMapping("genImg")
    public Object genImg() throws Exception {
        String certContent = "<div\n" +
                "      style=\"font-size: 18px; width: 1129px; height: 1080px\"\n" +
                "    >\n" +
                "      <img\n" +
                "        src=\"https://ambient-oss.oss-cn-hangzhou.aliyuncs.com/ambientMonitor/2022-8-10/206552224963489792-172195806769475584-我是一张图片配送中心中文-aa (1).png\"\n" +
                "      />\n" +
                "      <div\n" +
                "        data-v-4bb9aaf9=\"\"\n" +
                "        id=\"id-1660012069401\"\n" +
                "        data-type=\"text\"\n" +
                "        style=\"\n" +
                "          position: absolute;\n" +
                "          top: 99px;\n" +
                "          left: 131px;\n" +
                "          z-index: 10;\n" +
                "          user-select: auto;\n" +
                "        \"\n" +
                "      >\n" +
                "        <div data-v-4bb9aaf9=\"\" class=\"content-area\"><p>${考生姓名}</p></div>\n" +
                "        <!---->\n" +
                "      </div>\n" +
                "      <div\n" +
                "        data-v-4bb9aaf9=\"\"\n" +
                "        class=\"template-item draggable resizable vdr\"\n" +
                "        id=\"id-1660012916647\"\n" +
                "        data-type=\"text\"\n" +
                "        style=\"\n" +
                "          position: absolute;\n" +
                "          top: 206px;\n" +
                "          left: 135px;\n" +
                "          z-index: 10;\n" +
                "          user-select: auto;\n" +
                "        \"\n" +
                "      >\n" +
                "        <div data-v-4bb9aaf9=\"\" class=\"content-area\"><p>${考生账号}</p></div>\n" +
                "        <!---->\n" +
                "      </div>\n" +
                "      <div\n" +
                "        data-v-4bb9aaf9=\"\"\n" +
                "        class=\"template-item draggable resizable vdr\"\n" +
                "        id=\"id-1660013215057\"\n" +
                "        data-type=\"image-face\"\n" +
                "        style=\"\n" +
                "          position: absolute;\n" +
                "          top: 296px;\n" +
                "          left: 133px;\n" +
                "          z-index: 10;\n" +
                "          user-select: auto;\n" +
                "          width: 220px;\n" +
                "          height: 282px;\n" +
                "        \"\n" +
                "      >\n" +
                "        <div\n" +
                "          data-v-4bb9aaf9=\"\"\n" +
                "          class=\"content-area\"\n" +
                "          style=\"width: 100%; height: 100%\"\n" +
                "        >\n" +
                "          <div style=\"width: 100%; height: 100%\">\n" +
                "            \\n\n" +
                "            <div\n" +
                "              class=\"img\"\n" +
                "              style=\"\n" +
                "                width: 100%;\n" +
                "                height: 100%;\n" +
                "                background: url(https://train.dictech.com.cn/site/static/images/face-sample.jpg) center center / cover;\n" +
                "              \"\n" +
                "            ></div>\n" +
                "            \\n\n" +
                "          </div>\n" +
                "        </div>\n" +
                "      </div>\n" +
                "    </div>";

        String htmlStr =
                "<!DOCTYPE html><html><head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0\">\n  <title></title>\n <style type=\"text/css\">\n body {margin:0}\n p {margin:0}\n </style></head><body>"
                        + certContent
                        + "</body></html>";



        String path = "/root/phantomjs/html/test.html"; // html文件所在地址

        FileUtils.uploadInputStreamFile(path, htmlStr.getBytes("utf-8")); // 保存html代码到指定html文件

        String result = FileUtils.parseHtml2Pdf(path);

        System.out.println("result=> " + result);

        return result;
    }

}

FileUtils

public class FileUtils {

    /**
     * 将html源码写成 html文件,并保存该文件
     * @param path
     * @param bytes
     */
    public static void uploadInputStreamFile(String path, byte[] bytes) {

        File file = new File(path);

        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {

            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);

            bos.write(bytes);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    public static String parseHtml2Pdf(String url) throws IOException {
        System.out.println(url);
        Runtime rt = Runtime.getRuntime();
        // Process p = rt.exec("/home/phantomjs/bin/phantomjs /home/phantomjs/bin/html2pdf.js " + url);
        // Process p = rt.exec("D:\\phantomjs\\bin\\phantomjs D:\\phantomjs\\bin\\html2pdf.js " + url);
        System.out.println(url);
        // windows环境
        // Process p = rt.exec("D:\\phantomjs\\bin\\phantomjs D:\\projects\\demo-cert\\src\\main\\resources\\phantomjs\\bin\\html2pdf.js " + "file:///" + url);
        // linux环境
        Process p = rt.exec("/root/phantomjs/bin/phantomjs /root/phantomjs/bin/html2pdf.js " + "file:///" + url);
        InputStream is = p.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuffer sbf = new StringBuffer();
        String tmp = "";

        while((tmp = br.readLine()) != null) {
            sbf.append(tmp);
        }

        String resultstr = sbf.toString();
        System.out.println("resultstr:" + resultstr);
        String[] arr = resultstr.split("\\$");
        String result = "";
        String[] var10 = arr;
        int var11 = arr.length;

        for(int var12 = 0; var12 < var11; ++var12) {
            String s = var10[var12];
            if (s.endsWith("png")) {
                result = s;
            }
        }

        return result;
    }



}

不能强制修改图片后缀,否则生成的证书图片中不能正常显示

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值