javascript 使用 mpdf 通过 AJAX 生成 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22776985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating PDF via AJAX using mpdf
提问by C. Cahill
I'm using the mpdf libraryto generate a PDF of user-generated html. I can get the PDF to save to the server successfully, but I want the PDF to open in the browser for the user. I've tried using mpdf's output options to open the file in the browser or to prompt a download, but neither happens when I use AJAX to send the html data to the script.
我正在使用mpdf 库来生成用户生成的 html 的 PDF。我可以将 PDF 成功保存到服务器,但我希望 PDF 在浏览器中为用户打开。我尝试使用 mpdf 的输出选项在浏览器中打开文件或提示下载,但是当我使用 AJAX 将 html 数据发送到脚本时,这两种情况都没有发生。
Here's my AJAX:
这是我的 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');
},
})
});
Here's my PDF-generating script:
这是我的 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;
?>
I'm using AJAX so that the PDF can be created without having to navigate away from the page. Is there an error in my code or should I be using a different approach?
我正在使用 AJAX,以便无需离开页面即可创建 PDF。我的代码中是否有错误,还是应该使用不同的方法?
采纳答案by C. Cahill
I ended up not using AJAX and instead added a hidden input on the form and populated it using the following script:
我最终没有使用 AJAX,而是在表单上添加了一个隐藏的输入并使用以下脚本填充它:
$('#save').click(function() {
event.preventDefault();
var shelf_clone = $('#shelf').clone();
var shelf = shelf_clone.prop('outerHTML');
$('#save_shelf input[name=shelf]').val(shelf);
$('#save_shelf').submit();
});
回答by Sajitha Rathnayake
To indicate to the browser that the file should be viewed in the browser
向浏览器指示应在浏览器中查看该文件
Content-Type: application/pdf
Content-Disposition: inline; filename.pdf
To have the file downloaded rather than viewed
下载文件而不是查看文件
Content-Type: application/pdf
Content-Disposition: attachment; filename.pdf
<meta http-equiv="Content-Type" content="application/pdf; charset=utf-8">
Or using php
或者使用php
header('Content-Type: application/pdf');
header('Content-Description: inline; filename.pdf');