Empty Pdf file generated with FPDF library in WordPress plugin

I am currently implementing a pdf export functionality within a wordpress plugin i'm developing but the pdf file generated when i click on export button is empty. To implement the export i use FPDF library

Ive put the code which uses FPDF in a function which is executed by the wp_ajax_ action hook. Here is the code:

?php

require_once plugin_dir_path( __FILE__ ) . 'fpdf/fpdf.php';

function pdf_pull_wpse_212972() {

  $pdf = new FPDF('p','mm','a4');
  $pdf-SetFont('arial','b',14);
  $pdf-AddPage();
  $pdf-Cell(40,10,'Referrer URL',1,0,'C');
  $pdf-Cell(40,10,'User IP Address',1,0,'C');
  $pdf-Cell(40,10,'User Agent',1,0,'C');
  $pdf-Cell(40,10,'Browser',1,0,'C');
  $pdf-Cell(40,10,'OS',1,0,'C');
  $pdf-Output();

  wp_die();

}

add_action('wp_ajax_pdf_pull','pdf_pull_wpse_212972'); 

Here is the jQuery code executed when i click on the export button

jQuery(document).ready(function($) {

  
  jQuery('#pdf-export-btn').click(function(){

    var data = {
      'action': 'pdf_pull',
    };
    
    jQuery.post(tclisecure.ajax_url, data, function(response) {


        var downloadLink = document.createElement(a);
        var fileData = [response];

        var blobObject = new Blob(fileData,{
            type: application/pdf
          });

        var url = URL.createObjectURL(blobObject);
        downloadLink.href = url;
        downloadLink.download = tracked_info.pdf;

        /*
        * Actually download PDF
        */
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      
    });

  });


});

Topic plugin-development pdf Wordpress

Category Web


This might not solve the problem, but what you're currently doing looks unnecessarily convoluted (ajax request, fake link, serve PDF via link click etc.)

Why not just a link styled as a button...

<a class="button" href="<?= admin_url( 'admin-post.php?action=wpse_212972_pdf' ) ?>">Download</a>

...and then serve the PDF as a download directly from the server (using WP's generic POST/GET handler admin-post.php):

function wpse_212972_pdf() {
    $pdf = new FPDF('p','mm','a4');
    $pdf->SetFont('arial','b',14);
    $pdf->AddPage();
    $pdf->Cell(40,10,'Referrer URL',1,0,'C');
    $pdf->Cell(40,10,'User IP Address',1,0,'C');
    $pdf->Cell(40,10,'User Agent',1,0,'C');
    $pdf->Cell(40,10,'Browser',1,0,'C');
    $pdf->Cell(40,10,'OS',1,0,'C');

    // http://www.fpdf.org/en/doc/output.htm
    $pdf->Output( 'D', 'tracked_info.pdf' );
    exit;
}

add_action( 'admin_post_wpse_212972_pdf', 'wpse_212972_pdf' );

// Non-logged-in users (remove if not required)
add_action( 'admin_post_nopriv_wpse_212972_pdf', 'wpse_212972_pdf' );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.