获取PDFKit作为base64string

我正在寻找一种方法来获得PDFKit文档的base64string表示forms。 我不能find正确的方法来做到这一点…

这样的事情会非常方便。

var doc = new PDFDocument(); doc.addPage(); doc.outputBase64(function (err, pdfAsText) { console.log('Base64 PDF representation', pdfAsText); }); 

我已经尝试blob-stream lib,但它不能在节点服务器上工作(它说, Blob不存在)。

谢谢你的帮助!

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

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

 const PDFDocument = require('pdfkit'); const base64 = require('base64-stream'); // ... var doc = new PDFDocument(); // write to PDF var finalString = ''; // contains the base64 string var stream = doc.pipe(base64.encode()); 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); }); 

我刚刚为这个你可能使用的模块。 JS-的base64文件

 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}`); 

这是一个新的模块,所以我的文档还不完整,但也有一个asynchronous方法。

 //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文件回购请求