【问题标题】:Get PDFKit as base64 string获取 PDFKit 作为 base64 字符串
【发布时间】:2017-01-01 23:58:27
【问题描述】:

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

这样的东西会非常方便。

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

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

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

感谢您的帮助!

【问题讨论】:

    标签: node.js stream node-pdfkit


    【解决方案1】:

    我也遇到了类似的困境,想在没有临时文件的情况下即时生成 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);
    });
    

    【讨论】:

    • 太好了,谢谢!这正是我想要的,而且效果很好。
    【解决方案2】:

    我刚刚为此制作了一个您可能会使用的模块。 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

    上提交请求

    【讨论】:

    • 好的,谢谢!是的,内存会更好,因为我不想写在磁盘上。而且因为 de PdfDocument 是一个流,所以应该不会太难。我会检查你的回购。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    相关资源
    最近更新 更多