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

时间:2013-10-30 13:27:53

标签: php html ajax

尝试下载由发布的数据动态生成的文件。我有结果回来了。我只是不确定在从服务器返回信息(流)后如何将结果保存到本地的正确文件中。

这是ajax调用:

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);
                }
           });
}

从这样的超链接调用此函数,成功方法返回...

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

更新:以下是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 个答案:

答案 0 :(得分:2)

这不可能。只有你可以用这个PDF网址打开新的浏览器窗口或更改当前窗口的位置:window.location ='report_generation / downlaod_pdf.php';

答案 1 :(得分:0)

使用javascript / ajax无法做到这一点。您必须使用regural下载链接,或在您的案例表单中。如果你想使用javascript进行一些错误处理,如果pdf生成失败并且仍然打开同一页面,你可以提交到一个隐藏的iframe。

答案 2 :(得分:0)

您可以创建动态表单并提交它,它将打开一个新窗口/选项卡,如果失败,您可以在该页面中显示一条消息。无论如何,处理和跟踪异常的正确方法不在接收者身上,而是发送者(download_pdf.php)

创建动态表单:

var VerifyForm = document.createElement("form");
VerifyForm.target = "_blank"; //You must specify here your target
VerifyForm.method = "POST";
VerifyForm.action = "download_pdf.php";
var dataInput = document.createElement("input");
dataInput.type = "hidden";
dataInput.name = "mydata"; //var name
dataInput.value = value; //var value
VerifyForm.appendChild(dataInput); //Apend var to form, repeat for n
document.body.appendChild(VerifyForm);
VerifyForm.submit();

如果您仍然以自己的方式尝试,不可能,我建议您阅读更多关于“Ajax”中资本“A”的含义

答案 3 :(得分:0)

您可以尝试通过在downlaod_pdf.php

中添加这些HTTP标头来强制下载文件
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: public");
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=$your_file_name");
header("Content-Transfer-Encoding: binary");
readfile($your_file_content);

编辑:并在js文件中添加window.location.href = your_php_script_path