Generating PDF via AJAX using mpdf

2019-01-28 14:55发布

I'm using the mpdf library to 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.

Here's my 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:

<?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?

2条回答
相关推荐>>
2楼-- · 2019-01-28 15:23

I ended up not using AJAX and instead added a hidden input on the form and populated it using the following script:

$('#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();

});
查看更多
再贱就再见
3楼-- · 2019-01-28 15:29

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

header('Content-Type: application/pdf'); 
header('Content-Description: inline; filename.pdf'); 
查看更多
登录 后发表回答