我正在使用 mpdf library生成用户生成的 html 的 PDF。我可以让 PDF 成功保存到服务器,但我希望 PDF 在浏览器中为用户打开。我试过使用 mpdf 的输出选项在浏览器中打开文件或提示下载,但是当我使用 AJAX 将 html 数据发送到脚本时都没有发生。
这是我的 AJAX:
$('#save').click(function() {
var shelf_clone = $('#shelf').clone();
var shelf = shelf_clone.prop('outerHTML');
$.ajax({
type: "POST",
url: "pdf.php",
data: { html:shelf },
success: function(response)
{
$('#status').html('File Saved Successfully');
},
})
});
这是我的 PDF 生成脚本:
<?php
include_once('/mpdf/mpdf.php');
$html = $_POST['html'];
$mpdf=new mPDF();
$stylesheet = file_get_contents('css/print.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html,2);
$mpdf->Output('shelf.pdf', I);
exit;
?>
我正在使用 AJAX,因此无需离开页面即可创建 PDF。我的代码中有错误还是我应该使用不同的方法?
最佳答案
向浏览器表明该文件应该在浏览器中查看
Content-Type: application/pdf
Content-Disposition: inline; filename.pdf
下载而不是查看文件
Content-Type: application/pdf
Content-Disposition: attachment; filename.pdf
<meta http-equiv="Content-Type" content="application/pdf; charset=utf-8">
或者使用php
header('Content-Type: application/pdf');
header('Content-Description: inline; filename.pdf');
关于javascript - 使用 mpdf 通过 AJAX 生成 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22776985/