我正在寻找一种获取 PDFKit 文档的 Base64 字符串表示形式的方法。我找不到正确的方法......
这样的话就非常方便了。
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 的类似讨论帮助我到达了我需要的地方。基于此,我的解决方案类似于:
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);
});
const doc = new PDFDocument();
doc.text("Sample text", 100, 100);
doc.end();
const data = doc.read();
console.log(data.toString("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}`);
这是一个新模块,所以我的文档尚未完成,但还有一个异步方法。
//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}`);
}
);
我想我也可以添加从内存转换的方法。如果这不满足您的需求,您可以在
Grant 的回答,这是一种不使用节点响应而是承诺的替代方案(以简化路由器外部的调用):
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()
。