Download PDF from Base64 string


My situation (everything in PHP):

What I get: Base64 encoded string from the API.

What I need: a link to a link that downloads this document in PDF format. (I'm sure it will always be a PDF file)

I tried this:

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

but I kind of lost it, I can’t find a way to load it after decoding it.

I hope someone can help me, thanks in advance!

+4
source share
3 answers

An example here seems useful: 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 make the download happen.

+10
source

No need to decode base64. You can send the header with a 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; 
0

API , , .

$fakturaPDF = base64_decode($dane['result']['file']);  
// the name of the pdf file
$nazwaPDF = $dane['result']['name'];


    $file = $nazwaPDF;
// Open the file to get existing content
$current = file_get_contents($file);
// Write the contents back to the file
file_put_contents($file, $current);

if (file_exists($file)) {
    header('Content-Description: text');
    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;
}
0
source

Source: https://habr.com/ru/post/1623586/


All Articles