简体   繁体   中英

Creating a ajax that shows the PDF - using TCPDF

I'm using Laravel 4.2

Quite new to ajax and I don't know what to place in the .done to show the PDF.

What I have written in the method (missing the html variable... it's quite large) :

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    $pdf->SetCreator("Office");
    $pdf->SetAuthor('Office');
    $pdf->SetTitle('TCPDF Example 061');
    $pdf->SetSubject('TCPDF Tutorial');
    $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 061', PDF_HEADER_STRING);

    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    $pdf->SetMargins(10, 5, 10);
    $pdf->SetHeaderMargin(5);
    $pdf->SetFooterMargin(0);

    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
        require_once(dirname(__FILE__).'/lang/eng.php');
        $pdf->setLanguageArray($l);
    }

    $pdf->SetPrintHeader(false);
    $pdf->SetPrintFooter(false);

    $pdf->SetFont('helvetica', '', 10);

    $pdf->AddPage();

    $pdf->writeHTML($html, true, 0, true, 0);

    $pdf->lastPage();

    $pdf->Output('test.pdf', 'I');

What I have written in the view :

$('#btnPrint').click(function() {
    $.ajax({
        url: '{{ route('getPDF') }}',
        type: 'POST',
        cache: false,
        data: {data: html},
    })
    .done(function(data) {
        // what should be placed here
    })
    .fail(function() {
        console.log("error");
    });

});

This answer assumes that you are showing some sort of Loading icon while the PDF is generated:

jQuery cannot take the data given by the server and display nor save a PDF file.

What you need to do is something like this:

$('#btnPrint').click(function() {
    $.ajax({
        // This PHP file will generate the PDF and save it to your server
        // $pdf->Output('path/to/pdf/file.pdf', 'F');
        url: 'create_pdf.php', 
        type: 'POST',
        cache: false,
        data: {data: html},
    })
    .done(function(data) {
        $('#someDiv').html('<iframe src="path/to/pdf/file.pdf"></iframe>');
    })
    .fail(function() {
        console.log("error");
    });

});

This answer assumes that the PDF file generates very quickly and you do not need to show a loading icon at all:

$('#someDiv').html('<iframe src="create_pdf.php"></iframe>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM