简体   繁体   English

TCPDF - AJAX - 下载文件而不将其从AJAX调用保存到Web服务器

[英]TCPDF - AJAX - Download file without saving it to webserver from AJAX call

I have an AJAX call to the create_pdf.php page: 我有一个对create_pdf.php页面的AJAX调用:

$('body').on('click', '.PrintButtonWithClass', function (event) {
    var1 = $('#id1').val();
    var2 = $('#id2').val();
    dataString='var1='+var1+'&var2='+var2+'&pdf_name=PdfName&pdf_creator=myname';

    $.ajax({ 
        type: 'post',
        url: '/path/to/createpdf/file/create_pdf.php',
        data: dataString,
        success: function (data) {
            alert('success');
        }
    });
});

In create_pdf.php I tried to use this line to download the file: create_pdf.php我尝试使用此行下载文件:

$pdf->Output(str_replace(' ','_',utf8_decode($_POST['pdf_name'])).'.pdf', 'D');

I tried also the FD and I parameters with no success, the file does not get downloaded. 我也尝试了FDI参数没有成功,文件没有下载。

How can I force downloading the file created without saving it to the webserver and without redirecting user to any other page? 如何强制下载创建的文件而不将其保存到Web服务器并且不将用户重定向到任何其他页面? I want him to stay on the same page, and that the browser pops up a (download or preview dialog box) for the PDF. 我希望他留在同一页面上,浏览器弹出PDF的下载或预览对话框。 Is there any way to do it? 有什么办法吗?

EDIT : create_pdf.php is Waiting for POST variables. 编辑:create_pdf.php正在等待POST变量。 and uses them to create the HMTL for the pdf. 并使用它们为pdf创建HMTL。

You can try to submit the form to a new window( like a popup ): 您可以尝试将表单提交到新窗口(如弹出窗口):

<form method="post" id="myform" action="your_url">
    <input name="param1">
</form>

And in javascript 并在JavaScript中

// create popup window
var wind = window.open('about:blank', '__foo', 'width=700,height=500,status=yes,resizable=yes,scrollbars=yes');

// submit form to popup window
$("#myform").attr("target", "__foo");

Do not forget to send content-type header from php: 不要忘记从php发送内容类型标题:

header("Content-Type", "application/pdf");

Edit: Browsers should display your pdf content and also show download or print options. 编辑:浏览器应显示您的pdf内容,并显示下载或打印选项。 The code is not tested but I think it would do what you requested; 代码未经过测试,但我认为它会按照您的要求进行测试;

I found a work-around for my problem. 我找到了解决问题的方法。

I did an AJAX call inside another AJAX call. 我做了一个AJAX内另一个呼叫AJAX调用。

the first AJAX call creates the file on webServer and opens the file in a new Window. 第一个AJAX调用在webServer上创建文件,并在新窗口中打开该文件。

In his success parameter I do the following: 在他的成功参数中,我执行以下操作:

The second AJAX call that deletes the file from Server. 从服务器删除文件的第二个AJAX调用。

            $.ajax({ 
                type: 'post',
                url: '/path/to/create_pdf.php',
                data: dataString,
                success: function (data) {

                window.open(
                  data,
                  '_blank' // <- This is what makes it open in a new window.
                );


                window.setTimeout(function () {
                    dataString2 = 'Downloaded=true';
                            $.ajax({
                                type: 'post',
                                url: '/path/to/create_pdf.php',
                                data: dataString2,
                                success: function (data) { alert(data); }, // handler if second request succeeds 
                            });
                }, 5000);



                    },

                  });

Using this answer to my similar request : send a csv file from php to browser 使用这个答案我的类似请求: 从php发送一个csv文件到浏览器

I needed to (1) get and display a pdf in another window; 我需要(1)在另一个窗口中获取并显示pdf; and (2) get a CSV file and prompt for saving. (2)获取CSV文件并提示保存。

I have 2 simple buttons on the page ( http://potoococha.net/ ) for each. 我在页面上有两个简单的按钮( http://potoococha.net/ )。 Here is the code: 这是代码:

function getCSVText(evt)  {

  if (currentChecklistCountry)  {

    var form = $('<form method="post" action="../php/sendCSV.php?country=' + currentChecklistCountry + '"></form>');

    $('body').append(form);

    form.submit();

    form.remove();
  }
  else  checklistCountryButton.classList.add("needsAttention");
}

function openChecklistPage()  {

   if (!currentChecklistCountry)  {
       checklistCountryButton.innerHTML = "Select Country";
       checklistCountryButton.classList.add("needsAttention");
       return;
    }

   if (gNumDays == undefined) gNumDays = 12;

   vars = "?country="     + currentChecklistCountry;
   vars += "&num_days="   + gNumDays;
   vars += "&line_nos="   + lineNumbers.checked;
   vars += "&left_check=" + leftCheck.checked;
   vars += "&endemics="   + showEndemics.checked;
   vars += "&sci_names="  + !sciNames.checked;
   vars += "&italics="    + !italics.checked;

   window.open( '../php/makePDF.php' + vars, '_blank' );
}

So the getCSVText() methods downloads a file using a temporary form appended and then immediately removed, and openChecklistPage() successfully opens another browser window with a pdf file. 因此getCSVText()方法使用附加的临时表单下载文件,然后立即删除,openChecklistPage()成功打开另一个带有pdf文件的浏览器窗口。 The pdf file is never saved on the server. pdf文件永远不会保存在服务器上。 The CSV file is already stored there and just retrieved. CSV文件已存储在那里并刚刚检索。 Perhaps you can modify the code for your purposes. 也许您可以为您的目的修改代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM