Shamas S
Shamas S

Reputation: 7549

How to return a pdf object instead of saving using fpdf

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();

Upvotes: 2

Views: 12362

Answers (2)

Anthony
Anthony

Reputation: 37065

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");

Upvotes: 3

sabatmonk
sabatmonk

Reputation: 330

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

Upvotes: 7

Related Questions