Download PDFKit as a base64 string

I am looking for a way to get a base64 string representation of a PDFKit document. I cannot find the right way to do this ...

Something like this would be very convenient.

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

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

I already tried with blob-streamlib, but it does not work on the node server (it says it Blobdoes not exist).

Thank you for your help!

+4
source share
2 answers

I was in a similar predicament, wanting to generate PDFs on the fly without having temporary files. My context is the NodeJS API layer (using Express) that interacts with the React interface.

Ironically, a similar discussion

+5
source

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

, , async.

//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

0

Source: https://habr.com/ru/post/1652480/


All Articles