【问题标题】:Download PDF from Base64 string从 Base64 字符串下载 PDF
【发布时间】:2016-04-14 08:58:09
【问题描述】:

我的情况(全部在 PHP 中):

我得到:来自 API 的 Base64 编码字符串。

我想要的:点击链接可将此文档下载为 PDF。 (我相信它永远都是 PDF 文件)

我试过这个:

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

但我有点迷路了,解码后似乎找不到下载方法。

希望有人能帮助我,在此先感谢!

【问题讨论】:

    标签: php pdf base64


    【解决方案1】:

    不需要对 base64 进行解码。您可以发送带有二进制文件的标头。

    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; 
    

    【讨论】:

    • 这个解决方案完美无瑕,挽救了我的生命!谢谢!
    【解决方案2】:

    这里的例子似乎很有帮助:http://php.net/manual/en/function.readfile.php

    在你的情况下:

    <?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;
    }
    ?>
    

    这应该会强制进行下载。

    【讨论】:

    • 谢谢!这解决了我的问题。我现在面临的事实是,我的 PDF 文件已损坏,如果我将它放在链接中,我会收到“无法修改标题信息 - 标题已发送”,但我应该能够找到解决方法。一旦我为其他人得到答案,我会发布答案。如果您有任何提示,请告诉我,再次感谢!
    • 非常感谢。我添加了这行代码 unlink($file);在'退出;'之前因为我不希望文件永远存储在服务器中。
    猜你喜欢
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    相关资源
    最近更新 更多