PHP base64编码一个pdf文件
PHP base64 encode a pdf file
我正在使用 API,我可以将文档发送到 dropbox 之类的东西。根据文档,发送的文件需要是BASE64编码的数据。
因此,我正在尝试这样的事情
$b64Doc = chunk_split(base64_encode($this->pdfdoc));
其中 $this->pdfdoc
是我的 PDF 文档的路径。
目前正在发送文件,但似乎无效(什么都不显示)。
我是否正确地将 PDF 转换为 BASE64 编码数据?
谢谢
base64_encode()
将对您传递给它的任何字符串进行编码。如果您传递的值是文件名,那么您将获得的只是经过编码的文件名,而不是文件的内容。
您可能想先做 file_get_contents($this->pdfdoc)
或其他事情。
base64_encode
接受字符串输入。所以你所做的就是对路径进行编码。你应该抓取文件的内容
$b64Doc = chunk_split(base64_encode(file_get_contents($this->pdfdoc)));
将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;
}
我正在使用 API,我可以将文档发送到 dropbox 之类的东西。根据文档,发送的文件需要是BASE64编码的数据。
因此,我正在尝试这样的事情
$b64Doc = chunk_split(base64_encode($this->pdfdoc));
其中 $this->pdfdoc
是我的 PDF 文档的路径。
目前正在发送文件,但似乎无效(什么都不显示)。
我是否正确地将 PDF 转换为 BASE64 编码数据?
谢谢
base64_encode()
将对您传递给它的任何字符串进行编码。如果您传递的值是文件名,那么您将获得的只是经过编码的文件名,而不是文件的内容。
您可能想先做 file_get_contents($this->pdfdoc)
或其他事情。
base64_encode
接受字符串输入。所以你所做的就是对路径进行编码。你应该抓取文件的内容
$b64Doc = chunk_split(base64_encode(file_get_contents($this->pdfdoc)));
将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;
}