简体   繁体   English

将 PDF 二进制数据编码为 base64 不适用于 NodeJS

[英]Encoding PDF binary data to base64 not working with NodeJS

I'm trying to get a PDF stream return that comes from a API and parse it to base64 to embbed it in the client side, the body of the API request is returning something like this:我正在尝试获取来自 API 的 PDF stream 返回并将其解析为 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)

I'm trying to parse to base64 this way:我正在尝试以这种方式解析为 base64:

console.log(typeof body); // STRING
const encoded = new Buffer.from(body).toString('base64'); //PDF NOT WORKING

But when I'm getting this base64 and embedding it on the html it says that the file can't be oppened, the same thing happens when I trying to save it as.PDF file.但是,当我得到这个 base64 并将其嵌入到 html 时,它说无法打开该文件,当我尝试将其另存为 .PDF 文件时,也会发生同样的事情。

When I try to parse to base64 the same pdf but this time from a downloaded pdf, the base64 code when embedded in the html works fine.当我尝试将相同的 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
  });

I'm using const request = require('request');我正在使用const request = require('request'); to make the requests.提出要求。

When you make your request you should set option encoding to null for getting Buffer instead of String . 当您提出请求时,您应该将选项编码设置为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'))
})

I've found solution on this article .我在这篇文章中找到了解决方案。 You need add to your request some config.您需要在请求中添加一些配置。

axios.get({
    url: "https...",
    responseType: "arraybuffer",
    responseEncoding: "binary",
    headers: {
      "Content-Type": "application/pdf"
    }
});
const pdf2base64 = require('pdf-to-base64');
pdf2base64("test/sample.pdf")
    .then(
        (response) => {
            console.log(response);        }
    )
    .catch(
        (error) => {
            console.log(error);
        }
    )

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

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