How to return a pdf object instead of saving using fpdf

10,185

Solution 1

If I get the question correctly, you want the data stream?

If so, Output() take 2 parameters, name and destination. Sending S as destination parameter will return a string of the pdf data.

so, keeping your code

require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$file_contents = $pdf->Output("mypdf.pdf","S");

source

Solution 2

Per fdf Output() documentation:

Output([string name, string dest])

name

The name of the file. If not specified, the document will be sent to the browser (destination I) with the name doc.pdf.

dest

Destination where to send the document. It can take one of the following values:

  • I: send the file inline to the browser. The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.
  • D: send to the browser and force a file download with the name given by name.
  • F: save to a local file with the name given by name (may include a path).
  • S: return the document as a string. name is ignored.

So if you want to pass the file contents to variable, use:

$pdf_file_contents = $pdf->Output("","S");
Share:
10,185
Shamas S
Author by

Shamas S

Updated on June 14, 2022

Comments

  • Shamas S
    Shamas S almost 2 years

    I need to create a pdf file and send with a POST request to a server. For creating pdf, the code is very simple

    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output("mypdf.pdf");
    

    For POSTing, I read the pdf file by

    $file_contents = file_get_contents("mypdf.pdf");
    

    Is there a way that I don't have to first write to file and then read back from it? Some way of doing

    $file_contents = $pdf->Output();
    
  • Felix
    Felix about 5 years
    can I use this also in as return value of an ajax call?
  • shary.sharath
    shary.sharath over 3 years
    is there any way to create this PDF directly on Azure storage?