创建显示 PDF 的 ajax - 使用 TCPDF

Creating a ajax that shows the PDF - using TCPDF

我正在使用 Laravel 4.2

对 ajax 很陌生,我不知道在 .done 中放置什么来显示 PDF。

我在方法中写的(缺少html变量...它相当大):

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

我在视图中写了什么

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

});

此答案假定您在生成 PDF 时显示某种加载图标:

jQuery 无法获取服务器提供的数据并显示或保存 PDF 文件。

你需要做的是这样的:

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

});

此答案假定 PDF 文件生成速度非常快,您根本不需要显示加载图标:

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