1天精通wkhtmltopdf-java调用实战

1天精通wkhtmltopdf-java调用实战,第1张

html" class="superseo">java调用实战

该wkhtmltopdf只做了简单的封装装,基本满足单个文件生成、批量生成、文档合并等功能,这里只展示了部分代码,如需全部代码请到该链接下载https://download.csdn.net/download/u010913170/85336249
完整jar包下载路径.

关键代码展示 wkhtmltopdf可选参数
  1. d大纲参数选项
	package com.example.wkhtmltopdf.builder;

import com.example.wkhtmltopdf.builder.constant.OrientationEnum;
import com.example.wkhtmltopdf.builder.constant.PaperSizeEnum;

import java.util.Optional;

/**
 * 大纲参数选项
 */
public class GlobalOptions {

    private GlobalOptions() {}

    public static class Builder{
        private StringBuilder command = new StringBuilder();

        /**
         * 显示最详细的说明文档
         * @return
         */
        public Builder extendedHelp(){
            command.append(" -H ");
            return this;
        }

        /**
         * 简洁的帮助文档
         * @return
         */
        public Builder help(){
            command.append(" -h ");
            return this;
        }
......
    }
}

  1. 页眉和页脚参数选项
	package com.example.wkhtmltopdf.builder;

/**
 * 页眉和页脚参数选项
 */
public class HeadersAndFooterOptions {

    private HeadersAndFooterOptions() {}

    public static class Builder {
        private StringBuilder command = new StringBuilder();

        /**
         * 页脚文字居中
         *
         * @return
         */
        public Builder footerCenter(String text) {
            command.append(" --footer-center ").append(text);
            return this;
        }

        /**
         * 设置页脚的字体 (默认为 Arial)
         *
         * @return
         */
        public Builder footerFontName(String name) {
            command.append(" --footer-font-name ").append(name);
            return this;
        }
......
    }
}

  1. 大纲参数选项
	package com.example.wkhtmltopdf.builder;

/**
 *  大纲参数选项
 */
public class OutlineOptions {
    private OutlineOptions() {}

    public static class Builder {
        private StringBuilder command = new StringBuilder();

        /**
         * 输出默认的 TOC xsl 样式表到标准输出
         * @return
         */
        public Builder dumpDefaultTocXsl(){
            command.append(" --dump-default-toc-xsl ");
            return this;
        }
......
    }
}

  1. 页面对象参数
package com.example.wkhtmltopdf.builder;

import com.example.wkhtmltopdf.builder.constant.HandlerEnum;

/**
 * 页面对象参数
 */
public class PageOptions {

    private PageOptions() {}

    public static class Builder {
        private StringBuilder command = new StringBuilder();

        /**
         * 禁止智能收缩策略
         *
         * @return
         */
        public Builder disableSmartShrinking() {
            command.append(" --disable-smart-shrinking ");
            return this;
        }

        /**
         * 开启智能收缩策略(默认)
         *
         * @return
         */
        public Builder enableSmartShrinking() {
            command.append(" --enable-smart-shrinking ");
            return this;
        }
......
    }
}

  1. 目录对象参数
package com.example.wkhtmltopdf.builder;

/**
 * 目录对象参数
 */
public class TOCOptions {

    private TOCOptions() {}

    public static class Builder {
        private StringBuilder command = new StringBuilder();

        /**
         * 在目录中不使用虚线
         *
         * @return
         */
        public Builder disableDottedLines() {
            command.append(" --disable-dotted-lines ");
            return this;
        }
......
    }
}

  1. 常用的参数
package com.example.wkhtmltopdf.builder.commoncommands;

import com.example.wkhtmltopdf.builder.constant.OrientationEnum;
import com.example.wkhtmltopdf.builder.constant.PaperSizeEnum;

import java.util.Optional;

public class CommonCommands {

    private CommonCommands() {}

    public static class Builder{
        private StringBuilder command = new StringBuilder();
        /**
         * 设置页面高度  参数的值得单位默认是mm
         * @param pageHeight  页面高度
         * @return
         */
        public Builder pageHeight(String pageHeight){
            command.append(" --page-height ").append(pageHeight);
            return this;
        }
......
    }
}

WkHtmlToPdf统一调用入口
package com.example.wkhtmltopdf.builder;

import com.example.wkhtmltopdf.pojo.PathConfig;
import com.example.wkhtmltopdf.util.FileUtils;
import com.example.wkhtmltopdf.util.WkHtmlToPdfUtil;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class WkHtmlToPdfBuilder {

    public static class Builder{
        /**
         * wkHtmlToPdf工具路径
         */
        private String wkHtmlToPdfPath = null;
        /**
         * html路径
         */
        private String htmlPath = null;

        /**
         * 批量html
         */
        private List htmlPathList;

        /**
         * html生成pdf后合并成一个pdf
         */
        private boolean mergePdfFlag = false;

        /**
         * html合并完成之后生成pdf标识
         */
        private boolean mergeHtmlFlag = false;
        /**
         * 生成pdf路径
         */
        private String pdfPath = "";
        /**
         * 批量文件生成
         */
        private List<PathConfig> pathConfigList;

        /**
         * 批量处理标识
         */
        private boolean batchFlag = false;

        private String globalOptions = "";
        private String outlineOptions = "";
        private String pageOptions = "";
        private String headersAndFooterOptions = "";
        private String tocOptions = "";
        private String commonCommands;
        /**
         * 扩展
         */
        private String extend;

        public Builder(){
            this.wkHtmlToPdfPath = WkHtmlToPdfUtil.getInstallPath();
        };

        public Builder(String htmlPath, String pdfPath) {
            this.htmlPath = htmlPath;
            this.pdfPath = pdfPath;
            this.wkHtmlToPdfPath = WkHtmlToPdfUtil.getInstallPath();
        }

        public Builder globalOptions(String globalOptions){
            this.globalOptions = globalOptions;
            return this;
        }

        public Builder pageOptions(String pageOptions){
            this.pageOptions = pageOptions;
            return this;
        }

        public Builder headersAndFooterOptions(String headersAndFooterOptions){
            this.headersAndFooterOptions = headersAndFooterOptions;
            return this;
        }

        public Builder tocOptions(String tocOptions){
            this.tocOptions = tocOptions;
            return this;
        }

        public Builder outlineOptions(String outlineOptions){
            this.outlineOptions = outlineOptions;
            return this;
        }

        public Builder commonCommands(String commonCommands){
            this.commonCommands = commonCommands;
            return this;
        }

        public Builder mergeHtml(List htmlPathList, String pdfPath){
            this.htmlPathList = htmlPathList;
            this.pdfPath = pdfPath;
            this.mergeHtmlFlag = true;
            return this;
        }

        public Builder mergePdf(List htmlPathList, String pdfPath){
            this.htmlPathList = htmlPathList;
            this.pdfPath = pdfPath;
            this.mergePdfFlag = true;
            return this;
        }

        public Builder batch(List<PathConfig> pathConfigList){
            this.pathConfigList = pathConfigList;
            File file = new File(WkHtmlToPdfUtil.getTempPath());
            if(!file.exists()){
                file.mkdirs();
            }
            this.batchFlag = true;
            return this;
        }

        public Builder extend(String extend){
            this.extend = extend;
            return this;
        }

        public String build() {
            StringBuilder command = new StringBuilder();
            StringBuilder setCommand = new StringBuilder();
            // 封装wk生成参数
            setCommand.append(globalOptions).append(" ")
                    .append(pageOptions).append(" ")
                    .append(headersAndFooterOptions).append(" ")
                    .append(tocOptions).append(" ")
                    .append(outlineOptions).append(" ");

            if(CollectionUtils.isEmpty(pathConfigList)){
                command.append(wkHtmlToPdfPath).append(" ")
                        .append(setCommand)
                        .append(htmlPath).append(" ")
                        .append(pdfPath).append(" ");
            }

            // 如果批量设置参数不为空,则执行批量
            if(!CollectionUtils.isEmpty(pathConfigList)){
                // 获取批量待执行命令
                String echoCommand =  getBatchCommand(setCommand,pathConfigList);
                command.append(echoCommand);
            }
            return command.toString();
        }

        public boolean commit() throws Exception {
            StringBuilder command = new StringBuilder();
            StringBuilder setCommand = new StringBuilder();
            setCommand.append(globalOptions).append(" ")
                    .append(pageOptions).append(" ")
                    .append(headersAndFooterOptions).append(" ")
                    .append(tocOptions).append(" ")
                    .append(outlineOptions).append(" ");

            // 如果批量设置参数不为空,则执行批量
            if(batchFlag){
                // 获取批量待执行命令
                String echoCommand =  getBatchCommand(setCommand,pathConfigList);
                // 获取写入文件名称
                String tempPath = WkHtmlToPdfUtil.getTempFilePath();
                // 将命令写到文件中
                FileUtils.writeFile(new File(tempPath), echoCommand);
                return WkHtmlToPdfUtil.excuteCMDBatFile(tempPath);
            }

            // 先将所有html合并成一个html,再生成pdf
            if(mergeHtmlFlag){
                StringBuffer stringBuffer = new StringBuffer();
                for(int i=0; i<htmlPathList.size(); i++){
                    String htmlPath = (String) htmlPathList.get(i);
                    String s = FileUtils.readFile(new File(htmlPath));
                    stringBuffer.append(s);
                }
                // 获取临时文件
                String tempPath = WkHtmlToPdfUtil.getTempPath();
                // 临时文件名
                String htmlPath = tempPath+UUID.randomUUID() + ".html";
                // 将合并的html写到文件中
                boolean sucess = FileUtils.writeFile(new File(htmlPath), stringBuffer.toString());
                if(sucess){
                    command.append(wkHtmlToPdfPath).append(" ")
                            .append(setCommand)
                            .append(htmlPath).append(" ")
                            .append(pdfPath).append(" ");
                    return WkHtmlToPdfUtil.HTML2PDFbyexe(command.toString());
                }else{
                    throw new Exception("合并html失败,请检查相关信息!");
                }
            }

            // 先将单个html生成pdf,之后再将pdf合并成一个
            if(mergePdfFlag){
                List<String> list = new ArrayList<>();
                for(int i=0; i<htmlPathList.size(); i++) {
                    StringBuilder mergePdfCommand = new StringBuilder();
                    String htmlPath = (String) htmlPathList.get(i);
                    // 获取临时文件
                    String tempPath = WkHtmlToPdfUtil.getTempPath();
                    // 临时文件名
                    String pdfPath = tempPath+UUID.randomUUID() + ".pdf";
                    mergePdfCommand.append(wkHtmlToPdfPath).append(" ")
                            .append(setCommand)
                            .append(htmlPath).append(" ")
                            .append(pdfPath).append(" ");
                    // 调用生成pdf
                    boolean flag = WkHtmlToPdfUtil.HTML2PDFbyexe(mergePdfCommand.toString());
                    // 如果生成成功
                    if(flag){
                        list.add(pdfPath);
                    }else{
                        throw new Exception("生成pdf失败,请检查相关信息!");
                    }
                }
                return FileUtils.mergePDF(list, pdfPath);
            }

            command.append(wkHtmlToPdfPath).append(" ")
                    .append(setCommand)
                    .append(htmlPath).append(" ")
                    .append(pdfPath).append(" ");
            return WkHtmlToPdfUtil.HTML2PDFbyexe(command.toString());
        }

        /**
         * 获取批量执行的cmd命令
         * @param setCommand
         * @param pathConfigList
         * @return
         */
        private String getBatchCommand(StringBuilder setCommand, List<PathConfig> pathConfigList) {
            StringBuilder echoCommand = new StringBuilder();

            for(int i=0; i<pathConfigList.size(); i++){
                PathConfig pathConfig = pathConfigList.get(i);
                // 获取html路径
                String htmlPath = pathConfig.getHtmlPath().replace("\","\\");
                String pdfPath = pathConfig.getPdfPath().replace("\","\\");
                echoCommand.append(wkHtmlToPdfPath).append(" ")
                        .append(setCommand)
                        .append(htmlPath).append(" ")
                        .append(pdfPath);
                if(i!=pathConfigList.size()-1){
                    // 拼接换行
                    echoCommand.append(System.getProperty("line.separator"));
                }
            }
            return echoCommand.toString();
        }
    }
}
测试调用
package com.example.wkhtmltopdf;

import com.example.wkhtmltopdf.builder.WkHtmlToPdfBuilder;
import com.example.wkhtmltopdf.builder.commoncommands.CommonCommands;
import com.example.wkhtmltopdf.builder.constant.OrientationEnum;
import com.example.wkhtmltopdf.builder.constant.PaperSizeEnum;
import com.example.wkhtmltopdf.pojo.PathConfig;

import java.util.ArrayList;
import java.util.List;

public class WkHtmlToPdf {


    public static void main(String[] args) throws Exception {
//        long begin = System.currentTimeMillis();
//        for(int i=0;i<30;i++){
//            String commonCommands = new CommonCommands.Builder().orientation(OrientationEnum.landscape).pageSize(PaperSizeEnum.A1).build();
//            boolean flag = new WkHtmlToPdfBuilder.Builder("D:\404.html", "D:\wkhtmltopdf\gaoyuchao"+i+".pdf").commonCommands(commonCommands).commit();
//        }
//        long end = System.currentTimeMillis();
//        System.out.println(end-begin);
//
//
//
//
//        begin = System.currentTimeMillis();
//        String commonCommands = new CommonCommands.Builder().orientation(OrientationEnum.landscape).pageSize(PaperSizeEnum.A1).build();
//        List pathConfigList = new ArrayList<>();
//        for(int i=0;i<30;i++){
//            pathConfigList.add(
//                    PathConfig.builder()
//                            .htmlPath("D:\404.html")
//                            .pdfPath("D:\wkhtmltopdf\test"+i+".pdf").build()
//            );
//        }
//        boolean flag = new WkHtmlToPdfBuilder.Builder().commonCommands(commonCommands).batch(pathConfigList).commit();
//        end = System.currentTimeMillis();
//        System.out.println(end-begin);


        long begin = System.currentTimeMillis();
        String commonCommands = new CommonCommands.Builder().orientation(OrientationEnum.landscape).pageSize(PaperSizeEnum.A1).build();
        List<PathConfig> pathConfigList = new ArrayList<>();
        for(int i=0;i<30;i++){
            pathConfigList.add(
                    PathConfig.builder()
                            .htmlPath("D:\404.html")
                            .pdfPath("D:\wkhtmltopdf\test"+i+".pdf").build()
            );
        }
        List<Object> list = new ArrayList<>();
        list.add("D:\4041.html");
        list.add("D:\4041.html");
        list.add("D:\4041.html");
        list.add("D:\4041.html");
        list.add("D:\4041.html");
        list.add("D:\4041.html");
        boolean flag = new WkHtmlToPdfBuilder.Builder().commonCommands(commonCommands).mergePdf(list, "D:\wkhtmltopdf\test.pdf").commit();
        long end = System.currentTimeMillis();
        System.out.println(end-begin);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/904983.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-15
下一篇 2022-05-15

发表评论

登录后才能评论

评论列表(0条)

保存