java 根据html生成pdf 实现透明度

原项目中有在使用flying-saucer库来生成pdf,奈何不支持css3样式,然后遇到一个需求,客户要求设置透明度,然而百度一波,发现rgba 和 Opacity都是css3的,我当即就说这功能做不了。

说是说了,做还是得做,面向百度搜索了一波,发现了WKHtmlToPdf程序,于是开始安装
环境:centos7 x86_64

  1. wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox-0.12.6-1.centos7.x86_64.rpm
    其他版本看这里
  2. rpm2cpio wkhtmltox-0.12.6-1.centos7.x86_64.rpm | cpio -di
  3. yum install libXrender*
    yum install libfontconfig*
    yum install libXext*
  4. wkhtmltopdf.exe 1234.html ./1234.pdf

在这里插入图片描述
生成成功,
5. 设置环境变量
WKHTMLTOPDF_HOME=/data/usr/local/bin
6. 开始编码

public File htmlToPdfWKHtmlToPdf(String template, Map<String, Object> map) {
        Context context = new Context();
        context.setVariables(map);
        templateEngine.process(template, context);
        // 转义字符
        htmlcontext = htmlcontext.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
        // 创建临时文件
        FileUtils.fileWriteOut(htmlcontext.getBytes(), filePath, htmlFile);
        if (!flag) {
            throw new ServiceException("html文件写入硬盘失败!");
        }
        // 生成pdf
        String fullHtmlPath = filePath + "/" + htmlFile;
        boolean convert = convert(fullHtmlPath, fullPdfFile);
        if (!convert) {
            throw new ServiceException("html文件转换成pdf文件过程失败");
        }
        return new File(fullPdfFile);
    }

    public static boolean convert(String srcPath, String destPath) {
        File file = new File(destPath);
        File parent = file.getParentFile();
        // 如果pdf保存路径不存在,则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }
        StringBuilder cmd = new StringBuilder();
        // 获取环境变量
        String env = System.getenv(WKHTMLTOPDF_HOME);
        if (StringUtils.isEmpty(env)) {
            throw new ServiceException("环境变量{0}没有设置", WKHTMLTOPDF_HOME);
        }
        cmd.append(env);
        String os = System.getProperties().getProperty("os.name");
        if (os != null && os.toLowerCase().indexOf("linux") > -1) {
            cmd.append("/wkhtmltopdf");
        } else {
            cmd.append("/wkhtmltopdf.exe");
        }

        cmd.append(" ");
        cmd.append(srcPath);
        cmd.append(" ");
        cmd.append(destPath);

        boolean result = true;
        try {
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            proc.waitFor();
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }

参考链接:
https://www.cnblogs.com/IT-study/p/13706690.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值