Search code examples
wordpresspdffpdf

unable to see header after fpdf creates file


I am working on a wordpress plugin,

I want to create a pdf file, For this I used fpdf

By using this code I am able to generate pdf and save it to server

require('fpdf/html_table.php');
    $pdf=new PDF_HTML();
    $questions = $_POST['question'];
    $count = count($questions);
    $quests = "";
    $pdf->SetFont('times','',12);
    $pdf->SetTextColor(50,60,100);

    $pdf->AddPage('P');
    $pdf->SetDisplayMode(real,'default');

    $pdf->SetFontSize(12);

    for($i=1;$i<=$count;$i++)
    {
        $qus_id = $questions[$i-1];
        $get_q = "select * from `SelleXam_question` where `id`='$qus_id'";
        $get_q =  $wpdb->get_results($get_q);
        $questf = "Quest $i : ".$get_q[0]->question;
        $pdf->Cell(0, 10, $questf."\n");
        $pdf->Ln();
    }


        $dir='C:/wamp/www/';
        $filename= "filename.pdf";
        $pdf ->Output($dir.$filename);
        echo "Save PDF in folder";

But when it saved and displayed the messge Save PDF in Folder. I am unable to see the header part of the wordpress website.

Or when I use

$pdf->Output($filename,'D');

then is there any way that I can show the file in a link


Solution

  • When you are developing for Wordpress, you can't just echo text at any time. Wordpress has a whole series of actions it goes through to progressively generate the output rendered to the browser. If you generate output at an inappropriate time, you'll mess up Wordpress' ability to generate output at the right time.

    If I were developing this, I'd have this function be called as a filter on the_content. Your output code would change to something like this:

    function append_pdf_to_content($content) {
        //Your existing code
    
        $pdf->Output($filename, 'F');
        $pdf_link = "<br><a href='$filename' download>Download PDF</a>"
        return $content . $pdf_link;
    }
    
    add_filter('the_content', 'append_pdf_to_content');
    

    If you wanted to use the D option, you'll need to link your users to a separate php page using a target='_blank' that calls the download. Otherwise the PDFs headers will override any headers Wordpress is trying to send.

    BTW, you also might want to also take a look at mPDF, it's a fork of fpdf and remains in active development.