我如何使用 jQuery 将实时 php 生成的 PDF 交付给最终用户而不将其保存在服务器上?

How can I deliver a realtime-php-generated PDF to the Enduser using jQuery without saving it on the server?

我目前的设置: 我有一个 php 生成的 table,它显示了一些 "to-be-generated" pdf 的一些数据。每行都有一个复选框。复选框的 "checked" 唯一值被写入数组并发送到 createpdf.php - 文件。

计划是打开一个新的 window 并将 pdf 文件放入其中。

// put all the checked rows into array (e.g. "101,105,107")
$("#tools_savepdf").click(function(){
       arr_id = []; 
       $('.checkbox').each(function(){
            if ( $(this).is(':checked') ){
                arr_id[arr_id.length] = $(this).val();
            } 
       });

// open realtime-generated PDF

       $.ajax({
            type: "POST", 
            url: "createpdfs.php",
            data: { arr_id:arr_id },
            async: "true",
            success: function(data){
                var win = window.open();
                win.document.write(data);
            } //success
        }); //ajax

}); // click

问题是:生成的PDF打印到浏览器,如“%PDF-1.3 3 0 obj <> endobj 4 0 obj <> stream x��W��r��H��+ ...” .

我想把它作为文件。 P.S.: 在 ajax 中使用 mimetype-Parameter 没有帮助。

有没有我不知道的 ajaxify-to-file 选项?

我不明白你为什么要强制在浏览器中打开 Pdf window? 为什么您不强制下载或在创建后提供 link 下载它?

你无论如何都要把文件写到硬盘上,但你可以在下载后删除它。

/*Force the script to delete the file even if the browser is closed by the user*/
ignore_user_abort(true);

/*Force the download opening a save as dialog*/
$path = "path to file/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($path));
header('Content-Encoding: none');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . $filename);
readfile($path);


/*Remove the file from the hard drive*/
unlink($path);

这花费了很多威士忌和时间 :D 谢谢卢卡的回答。写入磁盘仍然不是一种选择,因为 "parking" 磁盘上的文件会在服务器端使用宝贵的毫秒数。

我将交易分为两部分,因为通过 ajax 发布所选 ID 在我(上面)发布的示例中不起作用。首先,我 Post 将值放入 $_SESSION - 变量中。然后(成功状态)我打开 link 到 php-PDF 生成器。

我所做的是创建一个服务器端文件,将 ID 存储到会话变量中:

writesession.php

session_start();
$_SESSION['arr_certificate_id']= $_POST['arr_id'];

ajaxified.php

 // put all the checked rows into array (e.g. "101,105,107")
 $("#tools_savepdf").click(function(){
        arr_id = []; 
        $('.checkbox').each(function(){
             if ( $(this).is(':checked') ){
                 arr_id[arr_id.length] = $(this).val();
             } 
        });

 // open realtime-generated PDF

        $.ajax({
             type: "POST", 
             url: "writesession.php",
             data: { arr_id:arr_id },
             async: "true",
             success: function(data){
                 window.open('createpdfs.php');
             } //success
         }); //ajax

 }); // click

然后我修改 pdfcreator 文件以读取会话变量。

createpdfs.php

$pdf_id_arr = $_SESSION['arr_certificate_id'];

[...]

现在 "createpdfs.php" 是一个硬 link 没有任何 "POSTS" 是工作得很好。