我试图获取来自API的PDF流并将其解析为base64以将其嵌入客户端,API请求的主体返回如下内容:
%PDF-1.5
%����
4 0 obj
<<
/Type/XObjcect
/Subtype/Image
/Width 799
/Height 70
/ColorSpace/DeviceGray
/BitsPerComponent 8
/Filter/FlateDecode
/Length 5181
>>
stream
x���=H#�������A�&�)���B���4iba�&O8H
.
.
.
(The rest was omitted)
我试图以这种方式解析为base64:
console.log(typeof body); // STRING
const encoded = new Buffer.from(body).toString('base64'); //PDF NOT WORKING
但是当我获得这个base64并将其嵌入到html中时,它表示该文件无法被禁用,当我尝试将其保存为.PDF文件时,会发生同样的事情。
当我尝试将相同的pdf解析为base64时,但这次是从下载的pdf中,嵌入在html中的base64代码工作正常。
fs.readFile('/home/user/downloaded.pdf', function (err, data) {
if (err) throw err;
console.log(typeof data); //OBJECT
const pdf = data.toString('base64'); //PDF WORKS
});
我使用const request = require('request');
发出请求。
答案 0 :(得分:6)
当您提出请求时,您应将选项编码设置为null,以获取Buffer
而不是String
。
request({
method: 'GET',
encoding: null,
uri: 'http://youdomain.com/binary.data'
}, (err, resp, data)=>{
console.log(typeof data) //should be an Object
console.log(data.toString('base64'))
})
答案 1 :(得分:0)
const pdf2base64 = require('pdf-to-base64');
pdf2base64("test/sample.pdf")
.then(
(response) => {
console.log(response); }
)
.catch(
(error) => {
console.log(error);
}
)