wkhtmltopdf 前端js到后端java调用

  • 安装

wkhtmltopdf官网地址下载:https://wkhtmltopdf.org/downloads.html

  • 前端js

预览:
function previewPdf(){
    var curwindurl=window.location.href;
    var url=clientpath+"/clientrest.jsp?op=previewpdf&url="+encodeURIComponent(encodeURIComponent(curwindurl));
    window.open(url,"","width=800px,height=600px,status=yes,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes");
}

下载:
function downloadFile(url) {   
    var curwindurl=window.location.href;
    var url=clientpath+"/clientrest.jsp?op=downloadpdf&url="+encodeURIComponent(encodeURIComponent(curwindurl));
    var elemIF = document.createElement("iframe");   
    elemIF.src = url;   
    elemIF.style.display = "none";   
    document.body.appendChild(elemIF);       
}

  • action逻辑

action里面处理逻辑
clientrest.jsp页面
else if("previewpdf".equals(op)){
            String url=request.getParameter("url");
            url = URLDecoder.decode(url, "utf-8");
            System.out.println(url);
            String pageId=CustomWKHtmlToPdfUtil.getPageId(url);
            String destinationPath= CustomWKHtmlToPdfUtil.TEMP_DIR_PATH + pageId + ".pdf";
            System.out.println(destinationPath);
            CustomWKHtmlToPdfUtil.htmlToPdf(url,destinationPath);
             // 设置输出文件为
            // 由于导出格式是excel的文件,设置导出文件的响应头部信息
            response.setContentType("application/pdf; charset=utf-8");
            response.setHeader("Content-Disposition", "filename=" + pageId + ".pdf"); 
            // 用response对象获取输出流
            File file = new File(destinationPath);
            InputStream proxyIn = null;
            OutputStream os = null;
            proxyIn = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] bos = new byte[proxyIn.available()];
            proxyIn.read(bos);
            os.write(bos);
            os.flush();
            if (os != null) {
                os.close();
                os=null;
                response.flushBuffer();
                out.clear();
                out=pageContext.pushBody();
                 
            }
            if (null != proxyIn) {
                proxyIn.close();
                proxyIn=null;            
            }
        }        
else if("downloadpdf".equals(op)){
    String url=request.getParameter("url");
    url = URLDecoder.decode(url, "utf-8");
    System.out.println(url);
    String pageId=CustomWKHtmlToPdfUtil.getPageId(url);
    String destinationPath= CustomWKHtmlToPdfUtil.TEMP_DIR_PATH + pageId + ".pdf";
    System.out.println(destinationPath);
    CustomWKHtmlToPdfUtil.htmlToPdf(url,destinationPath);
     // 设置输出文件为
    // 由于导出格式是excel的文件,设置导出文件的响应头部信息
    response.setContentType("application/pdf; charset=utf-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + pageId + ".pdf"); //attachment;会下载
    // 用response对象获取输出流
    File file = new File(destinationPath);
    InputStream proxyIn = null;
    OutputStream os = null;
    proxyIn = new FileInputStream(file);
    os = response.getOutputStream();
    byte[] bos = new byte[proxyIn.available()];
    proxyIn.read(bos);
    os.write(bos);
    os.flush();
    if (os != null) {
        os.close();
        os=null;
        response.flushBuffer();
        out.clear();
        out=pageContext.pushBody();
         
    }
    if (null != proxyIn) {
        proxyIn.close();
        proxyIn=null;            
    }
}

  • java调用

java 接口


import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

public class CustomWKHtmlToPdfUtil {
    // 临时目录的路径
    public static final String TEMP_DIR_PATH = CustomWKHtmlToPdfUtil.class.getResource("/").getPath().substring(1)
            + "temp/";

    static {
        System.out.println(TEMP_DIR_PATH);
        // 生成临时目录
        new File(TEMP_DIR_PATH).mkdirs();
    }    
    public static String getPageId(String url) {
        if (url == null || url.equals("")) {
            return null;
        }
        String pageId = null;
        String[] arr = url.split("&");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].contains("pageId")) {
                pageId = arr[i].split("=")[1];
                return pageId;
            }
        }
        return null;
    }

    /**
     * 将HTML文件内容输出为PDF文件
     *
     * @param htmlFilePath
     *            HTML文件路径
     * @param pdfFilePath
     *            PDF文件路径
     */
    public static void htmlToPdf(String htmlFilePath, String pdfFilePath) {
        try {
            Process process = Runtime.getRuntime().exec(getCommand(htmlFilePath, pdfFilePath));
            new Thread(new ClearBufferThread(process.getInputStream())).start();
            new Thread(new ClearBufferThread(process.getErrorStream())).start();
            process.waitFor();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获得HTML转PDF的命令语句
     *
     * @param htmlFilePath
     *            HTML文件路径
     * @param pdfFilePath
     *            PDF文件路径
     * @return HTML转PDF的命令语句
     */
    private static String getCommand(String htmlFilePath, String pdfFilePath) {
        String osName = System.getProperty("os.name");
        // Windows
        if (osName.startsWith("Windows")) {
            return String.format("D:/wkhtmltopdf/bin/wkhtmltopdf.exe %s %s", htmlFilePath, pdfFilePath);
        }
        // Linux
        else {
            return String.format("/opt/wkhtmltopdf/bin/wkhtmltopdf %s %s", htmlFilePath, pdfFilePath);
        }
    }
}

class ClearBufferThread implements Runnable {
    private InputStream inputStream;

    public ClearBufferThread(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while (br.readLine() != null)
                ;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值