dongwei1921 2013-10-30 13:27
浏览 175

如何将ajax结果保存为pdf文件?

Trying to download a file which is dynamically generated by the the data posted. I have the results coming back. I'm just not sure how I can save the results into a proper file locally once the information (stream) is returned from the server.

Here is the ajax call:

function download_pdf(){
      alert("made it" + result_array); 
      $.ajax({
                type: "POST",
                url: "report_generation/downlaod_pdf.php",
                data: { result_array: result_array },

                success: function(results){
                    alert(results);
                },
                error: 
                    function(xmlHttpRequest, status, error){
                        alert(xmlHttpRequest + "| ajax failure: could not download haq report | " + status + " | error:" + error);
                        var xmlHttpRequestStr = "";
                        for(var x in xmlHttpRequest)
                            xmlHttpRequestStr = xmlHttpRequestStr + xmlHttpRequest[x];
                        alert(xmlHttpRequestStr);
                }
           });
}

This function is called from a hyperlink like so, and the success method is returning...

<a class="haq_button" href="javascript:download_pdf()"><span>Download Report As PDF</span></a>

UPDATE: Here is a snippet of code from the file generation in download_pdf

// set the headers, prevent caching
            header("Pragma: public");
            header("Expires: -1");
            header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0");
            header("Content-Disposition: attachment; filename=\"$file_name\"");

            // set appropriate headers for attachment or streamed file
            if ($is_attachment) {
                    header("Content-Disposition: attachment; filename=\"$output_file_name\"");
            }
            else {
                    header('Content-Disposition: inline;');
                    header('Content-Transfer-Encoding: binary');
            }

            // set the mime type based on extension, add yours if needed.
            $ctype_default = "application/octet-stream";
            $content_types = array(
                    "exe" => "application/octet-stream",
                    "pdf" => "application/pdf",
                    "zip" => "application/zip",
                    "mp3" => "audio/mpeg",
                    "mpg" => "video/mpeg",
                    "avi" => "video/x-msvideo",
            );
            $ctype = isset($content_types[$file_ext]) ? $content_types[$file_ext] : $ctype_default;
            header("Content-Type: " . $ctype);

            //check if http_range is sent by browser (or download manager)
            if(isset($_SERVER['HTTP_RANGE']))
            {
                list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);
                if ($size_unit == 'bytes')
                {
                    //multiple ranges could be specified at the same time, but for simplicity only serve the first range
                    //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
                    list($range, $extra_ranges) = explode(',', $range_orig, 2);
                }
                else
                {
                    $range = '';
                    header('HTTP/1.1 416 Requested Range Not Satisfiable');
                    exit;
                }
}
    else
    {
        $range = '';
}

        //figure out download piece from range (if set)
        list($seek_start, $seek_end) = explode('-', $range, 2);

    //set start and end based on range (if set), else set defaults
    //also check for invalid ranges.
    $seek_end   = (empty($seek_end)) ? ($file_size - 1) : min(abs(intval($seek_end)),($file_size - 1));
    $seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);

    //Only send partial content header if downloading a piece of the file (IE workaround)
    if ($seek_start > 0 || $seek_end < ($file_size - 1))
    {
        header('HTTP/1.1 206 Partial Content');
        header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$file_size);
        header('Content-Length: '.($seek_end - $seek_start + 1));
    }
    else
      header("Content-Length: $file_size");

    header('Accept-Ranges: bytes');

    set_time_limit(0);
    fseek($file, $seek_start);

    while(!feof($file)) 
    {
        print(@fread($file, 1024*8));
        ob_flush();
        flush();
        if (connection_status()!=0) 
        {
            @fclose($file);
            exit;
        }           
    }

    // file save was a success
    @fclose($file);
    exit;
  • 写回答

4条回答 默认 最新

  • drgwsx8405 2013-10-30 13:36
    关注

    This is not possible using javascript/ajax. You have to use regural download link, or in your case form. If you want to have some error handling using javascript if pdf generation fails and still keep the same page open, you can submit into a hidden iframe.

    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决