Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Generating PDF via AJAX using mpdf

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...