获取 PDFKit 作为 base64 字符串

Get PDFKit as base64 string

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

像这样会非常方便。

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

doc.outputBase64(function (err, pdfAsText) {
    console.log('Base64 PDF representation', pdfAsText);
});

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

感谢您的帮助!

我刚刚为此制作了一个模块,您可能会用到它。 js-base64-file

const Base64File=require('js-base64-file');
const b64PDF=new Base64File;
const file='yourPDF.pdf';
const path=`${__dirname}/path/to/pdf/`;

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

//save you PDF using the filename and path

//this will load and convert
const data=b64PDF.loadSync(path,file);
console.log('Base64 PDF representation', pdfAsText);

//you could also save a copy as base 64 if you wanted like so :
b64PDF.save(data,path,`copy-b64-${file}`);

这是一个新模块,所以我的文档还没有完成,但是还有一个异步方法。

//this will load and convert if needed asynchriouniously
b64PDF.load(
    path,
    file,
    function(err,base64){
        if(err){
            //handle error here
            process.exit(1);
        }
        console.log('ASYNC: you could send this PDF via ws or http to the browser now\n');

        //or as above save it here
        b64PDF.save(base64,path,`copy-async-${file}`);
    }
);

我想我也可以添加从内存转换的方法。如果这不符合您的需要,您可以在 base64 file repo

上提交请求

我遇到了类似的困境,想要在没有临时文件的情况下即时生成 PDF。我的上下文是一个 NodeJS API 层(使用 Express),它通过 React 前端与之交互。

具有讽刺意味的是,similar discussion for 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);
});