简体   繁体   English

如何使用ajax和TCPDF下载pdf

[英]How to download a pdf using ajax and TCPDF

My code works fine when I run the php script without ajax as a GET request. 当我运行没有ajax作为GET请求的php脚本时,我的代码工作正常。 I get prompted to download the rendered pdf and all is well. 我被提示下载渲染的pdf,一切都很顺利。 However, I need to use ajax because I need to send more info from an html page to the php script than can be handled in a GET request. 但是,我需要使用ajax,因为我需要从一个html页面发送更多信息到PHP脚本,而不是在GET请求中处理。

What do I need to put into my ajax to make this work? 我需要将什么内容放入我的ajax才能使其工作?

Thanks 谢谢

js JS

function makePDF()
{
var x;
if(window.event) // IE8 and earlier
    {
    x=event.keyCode;
    }
else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
    {
    x=event.which;
    }
keychar=String.fromCharCode(x);

alert(keychar);

if (keychar == 'p' || keychar == 'P')
{
    var charSheetHTML = characterSheet.innerHTML;

    $.ajax({ 
     url: 'pdf.php',
     data: {'charactersheet': charSheetHTML,},
     type: 'post',
     success: function (data) {**WHAT_DO_I_PUT_HERE??**},
     error: function (data) { alert("error\n" + data.toString()); }
    });
}
}

pdf.php pdf.php

<?php
include_once( "bxcharacter/PDFChar.php.inc" );
PDFChar();  
?>

PDFChar.hph.inc PDFChar.hph.inc

<?php

require_once('./tcpdf/tcpdf.php');

function PDFChar(){


 $pdf = new TCPDF();


 $pdf->AddPage('P');
 $pdf->writeHTML($_POST['charactersheet']);


 $pdf->Output("character.pdf", 'D');


}

?>

This is not an ajax solution, but you can send your data with this way and if no error occurs, your page will not change. 这不是ajax解决方案,但您可以通过这种方式发送数据,如果没有错误发生,您的页面将不会更改。

Create a form element with inputs hidden which contains your data you want to send: 创建一个隐藏输入的表单元素,其中包含您要发送的数据:

example format: 示例格式:

<form id="myForm" method="GET" action="pdf.php">
   <input type="hidden" name="data1" type="hidden" value="your JSON.stringify() data">
</form>

js code (call these where your ajax request is): js代码(调用你的ajax请求的地方):

var myForm =  '<form id="myForm" method="GET" action="pdf.php">';
    myForm += '<input type="hidden" name="data1" type="hidden" value="JSON.stringify() data">';
    myForm += '</form>';

$("body").append(myForm);   // temporarily appending 
$("#myData-form").submit(); // submitting form with data
$("#myData-form").remove(); // remove form after submit

And as you said, force download will force file to download and page will remain same. 正如您所说,强制下载将强制下载文件,页面将保持不变。 However, if an error occurs, your page will change of course. 但是,如果发生错误,您的页面当然会发生变化。

I don't know whether this is an effective way or not but in my case, this does the trick. 我不知道这是否是一种有效的方式,但在我的情况下,这就是诀窍。

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

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