从base64编码的数据字符串中获取PDF文件的PHP方法

49

我有一个base64编码的字符串,其中包含一个pdf文件。如何使用php从这个编码的字符串创建一个.pdf文件?

类似于在头函数中使用Content-type:application/pdf吗?

这是base64编码的字符串


1
可能是重复的问题:将Base64字符串转换为图像文件? - Félix Adriyel Gagnon-Grenier
2个回答

77

尝试这段代码

$pdf_base64 = "base64pdf.txt";
//Get File content from txt file
$pdf_base64_handler = fopen($pdf_base64,'r');
$pdf_content = fread ($pdf_base64_handler,filesize($pdf_base64));
fclose ($pdf_base64_handler);
//Decode pdf content
$pdf_decoded = base64_decode ($pdf_content);
//Write data back to pdf file
$pdf = fopen ('test.pdf','w');
fwrite ($pdf,$pdf_decoded);
//close output file
fclose ($pdf);
echo 'Done';

1
谢谢Samy,这就是我想要的..干杯..:) 但是我的问题收到了一个负面投票!我的问题有什么不对吗? - Jenson M John
1
对于DomPdf,我只需要$pdf_decoded = $domPdf->output()和从//Write data back to pdf file开始的代码行。(致相关人士) - s3c
它不能正常工作,我试图取消点赞这个答案,但我无法做到。 - UserOfStackOverFlow

36

通过这个,你可以创建和打开文件……但也许这不是问题的答案。

$data = base64_decode($this->Get(self::Body));
file_put_contents('file.pdf',$data);

答案是用标题回显内容:

$data = base64_decode($this->Get(self::Body));
header('Content-Type: application/pdf');
echo $data;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接