marcbachmann / node-html-pdf

This repo isn't maintained anymore as phantomjs got dreprecated a long time ago. Please migrate to headless chrome/puppeteer.
MIT License
3.56k stars 543 forks source link

make buffer to pdf again? #443

Open JustAMicrobe opened 6 years ago

JustAMicrobe commented 6 years ago

Hello there,

i want to use html-pdf to create a buffer to save in the database. Afterwards, i want to load this buffer from database and display the pdf to the user.

pdf.create(html).toBuffer(function(err, buffer){
  console.log(buffer);

  fs.createReadStream(buffer.path).pipe(fs.createWriteStream('./asdf.pdf'));
  buffer.toStream().pipe(fs.createWriteStream('./foo.pdf'));
});

i tried the above and many more but i can't seem to figure it out. Is there a simple way of doing this?

Thanks in advance Pascal

CodyCline commented 5 years ago

@JustAMicrobe I know this is really late, but I may have a solution to your problem. I'm unaware of what database you are using, but if you want to store your files as buffer try going about it this way. 1) First make the PDF generation logic into a function that resolves a promise.

const generatePDF = () => {
    return new Promise (
        (resolve, reject) => {
            pdf.create(html).toBuffer(error, buffer) => {
                if(error) { 
                    reject(error) 
                }
                else {
                    resolve(buffer)
                }
            }
        }
    )
}

2) Then use the function like this when writing to the database

generatePDF().then( (buffer) => {
    //Some kind of database logic to insert the buffer
    db.insert({ "file": buffer })
});

3) When writing this to a file again do it like this

const fs = require("fs");

const buffer = db.get("file": buffer"); //Somehow get the buffer you want to write
const wstream = fs.createWriteStream("my-file-output.pdf");

wstream.write(buffer)
wstream.end()

If you plan on sending the file converted from database buffer via email or other communication means, you'll need to base64 encode it. Hope that helps.