使用mpdf通过AJAX生成PDF

问题描述 投票:2回答:2

我正在使用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。我的代码中是否有错误,或者我应该使用不同的方法?

javascript php ajax pdf mpdf
2个回答
1
投票

向浏览器指示应在浏览器中查看该文件

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'); 

0
投票

我最终没有使用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();

});
© www.soinside.com 2019 - 2024. All rights reserved.