PHP base64 编码 pdf 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34182379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP base64 encode a pdf file
提问by katie hudson
I am using an API where I can send a document to something like dropbox. According to the documentation, the file which is sent needs to be BASE64 encoded data.
我正在使用 API,我可以在其中将文档发送到 Dropbox 之类的东西。根据文档,发送的文件需要是 BASE64 编码的数据。
As such, I am trying something like this
因此,我正在尝试这样的事情
$b64Doc = chunk_split(base64_encode($this->pdfdoc));
Where $this->pdfdoc
is the path to my PDF document.
$this->pdfdoc
我的 PDF 文档的路径在哪里。
At the moment, the file is being sent over but it seems invalid (displays nothing).
目前,文件正在发送,但似乎无效(不显示任何内容)。
Am I correctly converting my PDF to BASE64 encoded data?
我是否正确地将我的 PDF 转换为 BASE64 编码数据?
Thanks
谢谢
回答by Machavity
base64_encode
takes a string input. So all you're doing is encoding the path. You should grab the contents of the file
base64_encode
接受一个字符串输入。所以你所做的就是对路径进行编码。你应该抓取文件的内容
$b64Doc = chunk_split(base64_encode(file_get_contents($this->pdfdoc)));
回答by Ian
base64_encode()
will encode whatever string you pass to it. If the value you pass is the file name, all you are going to get is an encoded filename, not the contents of the file.
base64_encode()
将编码您传递给它的任何字符串。如果您传递的值是文件名,那么您将获得的只是一个编码的文件名,而不是文件的内容。
You'll probably want to do file_get_contents($this->pdfdoc)
or something first.
你可能想先file_get_contents($this->pdfdoc)
做某事。
回答by Mauricio Villalobos
Convert base64 to pdf and save to server path.
将 base64 转换为 pdf 并保存到服务器路径。
// Real date format (xxx-xx-xx)
$toDay = date("Y-m-d");
// we give the file a random name
$name = "archive_".$toDay."_XXXXX_.pdf";
// a route is created, (it must already be created in its repository(pdf)).
$rute = "pdf/".$name;
// decode base64
$pdf_b64 = base64_decode($base_64);
// you record the file in existing folder
if(file_put_contents($rute, $pdf_b64)){
//just to force download by the browser
header("Content-type: application/pdf");
//print base64 decoded
echo $pdf_b64;
}