JSP Servlet响应pdf到Jquery

时间:2017-02-13 11:20:45

标签: java jquery jsp pdf servlets

我有一个带有按钮的jsp页面,该链接位于servlet上,这会创建一个pdf文件作为响应的流。

protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    path = request.getServletContext().getRealPath("/");
    String pdfFileName = "foo.pdf";
    String contextPath = getServletContext().getRealPath(File.separator);
    File pdfFile = new File(path + pdfFileName);

    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
    response.setContentLength((int) pdfFile.length());

    FileInputStream fileInputStream = new FileInputStream(pdfFile);
    OutputStream responseOutputStream = response.getOutputStream();
    int bytes;
    while ((bytes = fileInputStream.read()) != -1) {
        responseOutputStream.write(bytes);
    }


}

jquery是

$(document).ready(function() {
    $(".getpdfbutton").click(function(){
        var currentRow=$(this).closest("tr");
        var col1=currentRow.find("td:eq(0)").html();
        var data3=col1;  
        alert(data3);   
        $.get("PDFerzeugen",{Spass:data3}, function(data) {
            /* window.location = data; */
            alert(data);
        }); 
    });

我将数据响应为base64,如何将其作为pdf文件下载?

1 个答案:

答案 0 :(得分:0)

我通过这个脚本解决了它

    function SaveToDisk(fileURL, fileName) {
    // for non-IE
    if (!window.ActiveXObject) {
        var save = document.createElement('a');
        save.href = fileURL;
        save.target = '_blank';
        save.download = fileName || 'unknown';

        var evt = new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': false
        });
        save.dispatchEvent(evt);

        (window.URL || window.webkitURL).revokeObjectURL(save.href);
    }

    // for IE < 11
    else if ( !! window.ActiveXObject && document.execCommand)     {
        var _window = window.open(fileURL, '_blank');
        _window.document.close();
        _window.document.execCommand('SaveAs', true, fileName || fileURL)
        _window.close();
    }
};