获取PDFKit作为base64字符串

rek*_*kam 6 stream node.js node-pdfkit

我正在寻找一种方法来获取PDFKit文档的base64字符串表示.我找不到正确的方法来做到这一点......

像这样的东西会非常方便.

var doc = new PDFDocument();
doc.addPage();

doc.outputBase64(function (err, pdfAsText) {
    console.log('Base64 PDF representation', pdfAsText);
});
Run Code Online (Sandbox Code Playgroud)

我已经尝试过使用blob-streamlib,但它在节点服务器上Blob不起作用(它说它不存在).

谢谢你的帮助!

Gra*_*lin 12

我处于类似的困境,想要动态生成PDF而不会有临时文件.我的上下文是一个NodeJS API层(使用Express),它通过React前端进行交互.

具有讽刺意味的是,Meteor类似讨论帮助我到达了我需要的地方.基于此,我的解决方案类似于:

const PDFDocument = require('pdfkit');
const { Base64Encode } = require('base64-stream');

// ...

var doc = new PDFDocument();

// write to PDF

var finalString = ''; // contains the base64 string
var stream = doc.pipe(new Base64Encode());

doc.end(); // will trigger the stream to end

stream.on('data', function(chunk) {
    finalString += chunk;
});

stream.on('end', function() {
    // the stream is at its end, so push the resulting base64 string to the response
    res.json(finalString);
});
Run Code Online (Sandbox Code Playgroud)

  • 非常好,谢谢!这正是我想要的,而且效果很好。 (2认同)