Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download PDF from Base64 string

Tags:

php

pdf

base64


My situation (all in PHP):

What I get: A Base64 encoded string from an API.

What I want: A link to click on that downloads this document as an PDF. (I am sure it will always be a PDF file)

I have tried this:

    $decoded = base64_decode($base64);
    file_put_contents('invoice.pdf', $decoded);

but I am kind off lost, can't seem to find a way to download it after decoding it.

I hope someone can help me, thanks in advance!

like image 825
Marijn Roukens.com Avatar asked Jan 09 '16 19:01

Marijn Roukens.com


2 Answers

The example here seems helpful: http://php.net/manual/en/function.readfile.php

In your case:

<?php
$decoded = base64_decode($base64);
$file = 'invoice.pdf';
file_put_contents($file, $decoded);

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

This should force the download to occur.

like image 133
J. Titus Avatar answered Oct 27 '22 01:10

J. Titus


Don't need to decode base64. You can send header with binary file.

header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($filedata));
ob_clean();
flush();
echo $filedata;
exit; 
like image 21
Leocanis Avatar answered Oct 27 '22 01:10

Leocanis