简体   繁体   English

PHP base64编码pdf文件

[英]PHP base64 encode a pdf file

I am using an API where I can send a document to something like dropbox. 我正在使用API​​,我可以将文档发送到Dropbox之类的东西。 According to the documentation, the file which is sent needs to be BASE64 encoded data. 根据文档,发送的文件需要是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 谢谢

base64_encode takes a string input. base64_encode采用字符串输入。 So all you're doing is encoding the path. 所以你所做的只是编码路径。 You should grab the contents of the file 你应该抓住文件的内容

$b64Doc = chunk_split(base64_encode(file_get_contents($this->pdfdoc)));

base64_encode() will encode whatever string you pass to it. base64_encode()将编码传递给它的任何字符串。 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. 如果您传递的值是文件名,那么您将获得的是编码文件名,而不是文件的内容。

You'll probably want to do file_get_contents($this->pdfdoc) or something first. 您可能希望首先执行file_get_contents($this->pdfdoc)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM