将PDFKit作为base64字符串获取

11

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

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

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

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

我已经尝试使用blob-stream库,但它在Node服务器上无法工作(它说Blob不存在)。

感谢您的帮助!

4个回答

24
我曾经遇到类似的困境,希望能够在生成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);
});

2
非常好,谢谢!这正是我想要的,并且它完美地工作。 - rekam

4

文档中尚未提供同步选项

const doc = new PDFDocument();
doc.text("Sample text", 100, 100);
doc.end();
const data = doc.read();
console.log(data.toString("base64"));

0

参考Grant的答案,这里提供一种不使用节点响应而是使用Promise的替代方案(以便于在路由器外部调用):

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

const toBase64 = doc => {
    return new Promise((resolve, reject) => {
        try {
            const stream = doc.pipe(new Base64Encode());

            let base64Value = '';
            stream.on('data', chunk => {
                base64Value += chunk;
            });
            
            stream.on('end', () => {
                resolve(base64Value);
            });
        } catch (e) {
            reject(e);
        }
    });
};


被调用者在调用此异步方法之前或之后应使用 doc.end()

0

我刚刚为此制作了一个模块,你可能可以使用。 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文件仓库上提交请求。


好的,谢谢!是的,内存中操作会更好,因为我不想写入磁盘。而且 PdfDocument 是一个流,所以应该不太难。我会检查你的代码库。 - rekam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接